1

Having an issue with my flutter project parsing a json response and returning null.

Trying to receive the latitude and longitude values of an address I input. When I print out the jsonresponse variable I get the correct data, but when I try to parse the json response, both lat and lng, result in null. What am I missing?

part of void method to retreive lat/lng:

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

Location class to parse 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
        }}]
Smooth
  • 31
  • 1
  • That doesn't look like well-formed JSON. You might have to pre-process it to either add curly braces around the whole thing, or get rid of that "results": – Randal Schwartz Apr 03 '21 at 05:40

1 Answers1

0

You have to change it like this:

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

It'll work. Because "results" give you a list, and your "location" data is at index [0] of that list., after accessing "location", you get a Map of lat and 'lng, Please try this and confirm.

Huthaifa Muayyad
  • 11,321
  • 3
  • 17
  • 49
  • Thanks for you answer. I tried your solution, but I get the error: "(NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: []("location"))" – Smooth Apr 04 '21 at 01:52