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}));
      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


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



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


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

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

Answered By – Hadrien Lejard

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *