jsonangulardartcharacter-encodingangular-dart

Dart Angular and JSON encoding


I'm having and encoding issue on the application I'm working on. Is written in Angular Dart with Spring Boot on the backend. Those are variables i use for the request, along the header with the charset specified.

static final _headers = {'Content-Type': 'application/json; charset=utf-8', "Access-Control-Allow-Origin": "Origin"};
Uri _loginUri = new Uri(scheme: 'http', host: "localhost", path: 'api/login', port: 8080);

This is how I call the method

 Future<LoginResponse> login(String tessera, String password) async {
    try {
      final response = await _http.post(_loginUri, headers: _headers,
      body: json.encode({"tessera" : tessera, "password" : password}));
      print(response.body);
      return LoginResponse.fromJson(json.decode(response.body));
    } catch (e) {
      throw _handleError(e);
    }
  }

class LoginResponse {
  String authToken;
  String sessionToken;
  int tessera;
  String firstName;
  String lastName;

  LoginResponse(this.authToken, this.tessera, this.firstName, this.lastName, this.sessionToken);

  factory LoginResponse.fromJson(Map<String, dynamic> response) {
    return LoginResponse(response['authToken'], response['tessera'], response['firstName'], response['lastName'], response['sessionToken']);
  }
}

This is the answer the server give me

{"errorMessage":null,"sessionToken":"2dc546d7-8f0a-435a-bc49-c64ae7de1d49","tessera":326,"firstName":"Valerio","lastName":"Borsò","error":false}

But after the decoding I get the field last name with bad characters instead of the ò.

{"errorMessage":null,"authToken":"2f69ad50-5124-44fd-8de0-54fb634a8435","sessionToken":"f46fd67b-735f-4384-86a5-72d2863dd2ab","tessera":326,"firstName":"Valerio","lastName":"Borsò","error":false}

Solution

  • The response.body is decoded using charset found in your response headers, but will decode with latin1 by default if nothing specified

    https://pub.dev/documentation/http/latest/http/Response/body.html

    You can try to decode the body yourself using utf8 (or something else)

     final responseBody = utf8.decode(response.bodyBytes);
     final jsonBody = json.decode(responseBody);