【问题标题】:Parsing Nested JSON Object Flutter解析嵌套的 JSON 对象 Flutter
【发布时间】:2023-04-02 21:21:01
【问题描述】:

我正在尝试解析 JSON 中的对象,并且我能够在没有嵌套 JSON 对象开放时间的情况下成功地解析。我不知道为什么。这是json数据:

{
    "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
        },}

我的班级是这样设置的:

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

然后我会在将来调用我的 api 以获取详细信息。这是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;
}

当我调用 api currentLocations = null 时。我在这里做错了什么?

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    最简单的方法之一是使用quicktype.io 生成 PODO(Plain Old Dart Objects)。只需选择 dart 语言来创建 PODO 并将您的 JSON 复制粘贴到那里,并将类名称提供为“位置”。我已经为您完成了,现在您的位置类将如下所示:

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

    这现在可能有效,如果仍然存在问题,那么您可能会从后端获得空值。

    【讨论】:

    • 那里只有一行有问题。谢谢!
    • 不客气。另外,如果您认为答案相关,请点赞。
    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2020-05-21
    相关资源
    最近更新 更多