简体   繁体   中英

Parsing Nested JSON Object Flutter

I'm trying to parse an object in JSON and I am able to do so successfully without the nested JSON object Opening Hours. I don't know why. Here is the json data:

{
    "location": [
        {
            "id": 4,
            "location_name": "PastryMan",
            "cbd_products": "",
            "phone": "1231231234",
            "street_address": "535 7th Ave",
            "location_logo": "https://.s3.amazonaws.com/location_logo/water.png",
            "location_photo": "https://dispensaries.s3.amazonaws.com/location_photo/delta9.jpg",
            "sponsored_location": "Yes",
            "city": "New York",
            "state": "New York",
            "zip_Code": 10018,
            "lat": 40.7538935555556,
            "lng": -73.9883851111111,
            "latlng": "(40.7770112244898, -74.2110798163265)",
            "opening_hours": [
                {
                    "day_of_week": "Tuesday",
                    "opening_time": "08:00:00",
                    "closing_time": "22:00:00"
                },
                {
                    "day_of_week": "Wednesday",
                    "opening_time": "08:00:00",
                    "closing_time": "22:00:00"
                },
                {
                    "day_of_week": "Thursday",
                    "opening_time": "08:00:00",
                    "closing_time": "22:00:00"
                },
                {
                    "day_of_week": "Friday",
                    "opening_time": "08:00:00",
                    "closing_time": "22:00:00"
                },
                {
                    "day_of_week": "Saturday",
                    "opening_time": "08:00:00",
                    "closing_time": "22:00:00"
                },
                {
                    "day_of_week": "Sunday",
                    "opening_time": "08:00:00",
                    "closing_time": "22:00:00"
                },
                {
                    "day_of_week": 7,
                    "opening_time": "08:00:00",
                    "closing_time": "22:00:00"
                }
            ],
            "ratings": 0.0
        },}

I have setup my class like this:

class Location {
   int id;
  String name;
  String phone;
  String address;
  String city;
  String locationPhoto;
  String locationLogo;
  String state;
  num lat;
  num long;
  List<OpeningHours> openingHours;
  String cbdProducts;
  num rating;
  String zipCode;
  String latlng;
  String sponsored;

  location(
      {this.id,
      this.name,
      this.cbdProducts,
      this.phone,
      this.address,
      this.locationLogo,
      this.locationPhoto,
      this.sponsored,
      this.city,
      this.state,
      this.zipCode,
      this.lat,
      this.long,
      this.latlng,
      this.openingHours,
      this.rating});

  location.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['location_name'];
    cbdProducts = json['cbd_products'];
    phone = json['phone'];
    address = json['street_address'];
    locationLogo = json['location_logo'];
    locationPhoto = json['location_photo'];
    address = json['sponsored_location'];
    city = json['city'];
    state = json['state'];
    zipCode = json['zip_Code'];
    lat = json['lat'];
    long = json['long'];
    latlng = json['latlng'];
    if (json['opening_hours'] != null) {
      openingHours = new List<OpeningHours>();
      json['opening_hours'].forEach((v) {
        openingHours.add(new OpeningHours.fromJson(v));
      });
    }
    rating = json['ratings'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['location_name'] = this.name;
    data['cbd_products'] = this.cbdProducts;
    data['phone'] = this.phone;
    data['street_address'] = this.address;
    data['location_logo'] = this.locationLogo;
    data['location_photo'] = this.locationPhoto;
    data['sponsored_location'] = this.address;
    data['city'] = this.city;
    data['state'] = this.state;
    data['zip_Code'] = this.zipCode;
    data['lat'] = this.lat;
    data['lng'] = this.long;
    data['latlng'] = this.latlng;
    if (this.openingHours != null) {
      data['opening_hours'] = this.openingHours.map((v) => v.toJson()).toList();
    }
    data['ratings'] = this.rating;
    return data;
  }
}

class OpeningHours {
  String dayOfWeek;
  String openingTime;
  String closingTime;

  OpeningHours({this.dayOfWeek, this.openingTime, this.closingTime});

  OpeningHours.fromJson(Map<String, dynamic> json) {
    dayOfWeek = json['day_of_week'];
    openingTime = json['opening_time'];
    closingTime = json['closing_time'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['day_of_week'] = this.dayOfWeek;
    data['opening_time'] = this.openingTime;
    data['closing_time'] = this.closingTime;
    return data;
  }
}

Then I call my api in a future to get the details. Here is the api:

Future getLocations() async {
  var url = '$_server/api/customer/location/';
  HttpClient client = new HttpClient();
  HttpClientRequest request = await client.getUrl(Uri.parse(url));
  HttpClientResponse response = await request.close();
  String reply = await response.transform(utf8.decoder).join();

  var responseData = json.decode(reply);

  Locations _location = Locations.fromJson(responseData);
  currentLocations = _location.location;
  print(currentLocations);
  return _location.location;
}

When I call the api currentLocations = null. What have I done wrong here?

One of the easiest ways is to use quicktype.io to generate PODO (Plain Old Dart Objects). Just Select the dart language to create PODO and copy-paste your JSON over there and provide the class Name as "Location". I have done that for you now your location class will look like this:

class Location {
    Location({
        this.location,
    });

    List<LocationElement> location;

    factory Location.fromJson(Map<String, dynamic> json) => Location(
        location: List<LocationElement>.from(json["location"].map((x) => LocationElement.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "location": List<dynamic>.from(location.map((x) => x.toJson())),
    };
}

class LocationElement {
    LocationElement({
        this.id,
        this.locationName,
        this.cbdProducts,
        this.phone,
        this.streetAddress,
        this.locationLogo,
        this.locationPhoto,
        this.sponsoredLocation,
        this.city,
        this.state,
        this.zipCode,
        this.lat,
        this.lng,
        this.latlng,
        this.openingHours,
        this.ratings,
    });

    int id;
    String locationName;
    String cbdProducts;
    String phone;
    String streetAddress;
    String locationLogo;
    String locationPhoto;
    String sponsoredLocation;
    String city;
    String state;
    int zipCode;
    double lat;
    double lng;
    String latlng;
    List<OpeningHour> openingHours;
    int ratings;

    factory LocationElement.fromJson(Map<String, dynamic> json) => LocationElement(
        id: json["id"],
        locationName: json["location_name"],
        cbdProducts: json["cbd_products"],
        phone: json["phone"],
        streetAddress: json["street_address"],
        locationLogo: json["location_logo"],
        locationPhoto: json["location_photo"],
        sponsoredLocation: json["sponsored_location"],
        city: json["city"],
        state: json["state"],
        zipCode: json["zip_Code"],
        lat: json["lat"].toDouble(),
        lng: json["lng"].toDouble(),
        latlng: json["latlng"],
        openingHours: List<OpeningHour>.from(json["opening_hours"].map((x) => OpeningHour.fromJson(x))),
        ratings: json["ratings"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "location_name": locationName,
        "cbd_products": cbdProducts,
        "phone": phone,
        "street_address": streetAddress,
        "location_logo": locationLogo,
        "location_photo": locationPhoto,
        "sponsored_location": sponsoredLocation,
        "city": city,
        "state": state,
        "zip_Code": zipCode,
        "lat": lat,
        "lng": lng,
        "latlng": latlng,
        "opening_hours": List<dynamic>.from(openingHours.map((x) => x.toJson())),
        "ratings": ratings,
    };
}

class OpeningHour {
    OpeningHour({
        this.dayOfWeek,
        this.openingTime,
        this.closingTime,
    });

    dynamic dayOfWeek;
    String openingTime;
    String closingTime;

    factory OpeningHour.fromJson(Map<String, dynamic> json) => OpeningHour(
        dayOfWeek: json["day_of_week"],
        openingTime: json["opening_time"],
        closingTime: json["closing_time"],
    );

    Map<String, dynamic> toJson() => {
        "day_of_week": dayOfWeek,
        "opening_time": openingTime,
        "closing_time": closingTime,
    };
}

This may work now and if still there is issue then you may be getting null value from backend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM