1
votes

I'm facing an issue when trying to parse a json from an API and I'm hitting the error below.

Response response= await Dio().post(url ,data:{"login_credential":_tmp_email,'password' : _tmp_password});

if ( response.statusCode == 200 ){

  var parsedJson =  json.decode(response.data);
  print(parsedJson["result"]);
  print(response.data);
}

} catch (e) {
  print(e);
}

The error:

type '_InternalLinkedHashMap' is not a subtype of type 'String'

After some google searches and numerous tries of debugging. I came to a conclusion whereby it seems that the structure of the json returned is quite complex that's why parsing it normally will have problems.

The structure of the json is as follows.

{
result: 1, 
msg: Login Success, 
data: {
  access_token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvYXNpYS1hbGxuZXQuY29tXC9hcGlcL21vYmlsZS12MVwvYXV0aC5tYW51YWwubG9naW4iLCJpYXQiOjE1NTUxNjQ4OTIsImV4cCI6MTU1NTE2NTAxMiwibmJmIjoxNTU1MTY0ODkyLCJqdGkiOiJjRGtLTVNOMlBmUTdwYjgzIiwic3ViIjo2MTksInBydiI6Ijg2NjVhZTk3NzVjZjI2ZjZiOGU0OTZmODZmYTUzNmQ2OGRkNzE4MTgifQ.YlmzG5bMbXV2_pMa9v5oRItdVBpM878ocfiGD0YS6Zo, 
  token_type: bearer,
  expires_in: 119, 
  member: {
            name: john, email: [email protected], id: 619, avatar_url: 
            https://example.com/images/img_avatar.png
          }
       }
}
2

2 Answers

1
votes

Correct me if i'm wrong , I think I've got it guys , it seems that dio as http client already parses the json response that's why there is no need for json.decode.

I'm able to get data via accessing it through keys.

  print(response.data["result"]);
  print(response.data["data"]["member"]["name"]);
0
votes

As you have already guessed, Dio parses the response as json, if the Content-Type says so. From the documentation:

  /// [responseType] indicates the type of data that the server will respond with
  /// options which defined in [ResponseType] are `JSON`, `STREAM`, `PLAIN`.
  ///
  /// The default value is `JSON`, dio will parse response string to json object automatically
  /// when the content-type of response is "application/json".
  ///
  /// If you want to receive response data with binary bytes, for example,
  /// downloading a image, use `STREAM`.
  ///
  /// If you want to receive the response data with String, use `PLAIN`.
  ResponseType responseType;

if you want a string you can use _dio.post('...', data: ..., options: Options(responseType: ResponseType.plain))