在flutter中解析json时如何解决类型错误?

时间:2019-04-13 14:52:38

标签: json api flutter

尝试从API解析json时遇到问题,并且遇到了以下错误。

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

错误:

  

类型'_InternalLinkedHashMap'不是类型'String'的子类型

经过一些Google搜索和大量的调试尝试。我得出的结论是,似乎返回的json的结构非常复杂,这就是解析它通常会出现问题的原因。

json的结构如下。

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

2 个答案:

答案 0 :(得分:1)

如果我错了,请纠正我,我想我已经知道了,似乎作为http客户端的dio已经解析了json响应,这就是为什么不需要json.decode的原因。

我能够通过按键访问数据。

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

答案 1 :(得分:0)

您已经猜到了,如果Content-Type如此表示,Dio将响应解析为json。从文档中:

  /// [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;

如果您想要一个字符串,可以使用_dio.post('...', data: ..., options: Options(responseType: ResponseType.plain))