【问题标题】:Flutter Parse Json Returing NullFlutter Parse Json 返回 Null
【发布时间】:2021-06-29 16:51:59
【问题描述】:

我的颤振项目在解析 json 响应并返回 null 时遇到问题。

尝试接收我输入的地址的纬度和经度值。当我打印出 jsonresponse 变量时,我得到了正确的数据,但是当我尝试解析 json 响应时,lat 和 lng 都会导致 null。我错过了什么?

用于检索 lat/lng 的 void 方法的一部分:

var response = await http.get(request);
var jsonresponse = response.body;
Location location = Location.fromJson(jsonDecode(jsonresponse));
print(location.lat);
print(location.lng);

解析json的位置类:

class Location {
  double lat;
  double lng;

  Location({this.lat, this.lng});

  Location.fromJson(Map<String, dynamic> json) {
    lat = json['lat'];
    lng = json['lng'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['lat'] = this.lat;
    data['lng'] = this.lng;
    return data;
  }
}

Jsonresponse.body:

"results": [
    {
        "location": {
            "lat": 35.2323243,
            "lng": -80.234353
        }}]

【问题讨论】:

  • 这看起来不像是格式良好的 JSON。您可能必须对其进行预处理以在整个事物周围添加花括号,或者摆脱“结果”:

标签: json flutter parsing jsonresponse


【解决方案1】:

你必须像这样改变它:

var response = await http.get(request);
var jsonresponseDecoded = jsonDecode(response.body);
Location location = Location.fromJson(jsonresponseDecoded[0]['location']);
print(location.lat);
print(location.lng);

它会起作用的。因为"results" 给你一个列表,而你的"location" 数据位于该列表的索引[0]。访问“位置”后,你会得到lat 和'lng 的地图,请试试这个和确认。

【讨论】:

  • 感谢您的回答。我尝试了您的解决方案,但出现错误:“(NoSuchMethodError:方法'[]'在null上被调用。接收者:null尝试调用:[](“location”))”
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2020-08-23
  • 2021-09-28
  • 2020-11-10
  • 2020-07-12
  • 2021-06-14
  • 2020-07-18
  • 2021-02-20
相关资源
最近更新 更多