【问题标题】:How to fix type errors when parsing json in flutter?在flutter中解析json时如何修复类型错误?
【发布时间】:2023-03-22 09:21:01
【问题描述】:

我在尝试从 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”不是“字符串”类型的子类型

经过一些谷歌搜索和多次调试尝试。我得出一个结论,似乎返回的 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
          }
       }
}

【问题讨论】:

    标签: json api flutter


    【解决方案1】:

    如果我错了,请纠正我,我想我已经明白了,看起来作为 http 客户端的 dio 已经解析了 json 响应,这就是为什么不需要 json.decode。

    我可以通过密钥访问数据来获取数据。

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

    【讨论】:

    • 当你这样做时 var parsedJson = json.decode(response.data); parsedJson 变成了 key String 和 dynamic 值的映射,所以它不再是 json
    • 太好了!!
    【解决方案2】:

    正如您已经猜到的那样,如果 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))

    【讨论】:

      猜你喜欢
      • 2019-08-31
      • 2020-02-08
      • 2019-12-04
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 2021-10-16
      • 2018-06-05
      相关资源
      最近更新 更多