Json数据下降,但是对象为空

时间:2019-10-09 16:31:10

标签: json serialization flutter dart

我正在尝试将服务器中的JSON数据传递到Flutter中的预制对象中,但是即使将数据传递给变量和相应的类,我也会得到一个空值。

Future getPlaces() async{
  _isLoading = true;
  var url = 'http://Place-2212.herokuapp.com/api/customer/Locations/';

    http.get(url, headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  }).then((http.Response response)  {
    // print(response.body);

    final responseData = json.decode(response.body);


     Place place = Place.fromJSON(responseData);

    print(place.toJson());
    return Place;


  });

}

这里的输出是这样:

 {id: null, name: null, address: null, city: null, placePhoto: null, state: null, lat: null, long: null, rating: null}

我如何获取从json请求拉到我的对象中的数据?

更新1:

这是Place类的实现方式:

class Place {
  int id;
  String name;
  String address;
  String city;
  String restaurantPhoto;
  String state;
  double lat;
  double long;
  String rating;

  Place({
    this.id,
    this.address,
    this.city,
    this.restaurantPhoto,
    this.lat,
    this.long,
    this.name,
    this.state,
    this.rating,
  });

  factory Place.fromJSON(Map<String, dynamic> json){
     return Place(
    id: json['id'] as int,
    name: json[‘restaurant_name'] as String,
    address: json['street_address'] as String,
    city: json['city'] as String,
    restaurantPhoto: json['restaurant_photo'] as String,
    state: json['state'] as String,
    lat: json['lat'] as double,
    long: json['lng'] as double,
    rating: json['rating'] as String,
  );
  }
}

更新2:这是我要序列化的JSON响应。

{places: [{id: 4, place_name: The Oasis, phone: 123-123-1234, street_address: 456 Fake St, place_logo: https://restaurant.s3.amazonaws.com/restaurant_logo/restaurantLogo_jXon4qm.jpg, place_photo: https://restaurant.s3.amazonaws.com/restaurant_photo/farma.jpg, city: New York, state: New York, zip_Code: 12345, lat: 40.0, lng: 40.0, latlng: (40.7770112244898, -74.2110798163265), opening_hours: [], ratings: 3.0}, 

1 个答案:

答案 0 :(得分:1)

您需要根据要接收的JSON的结构实现Place.fromJSON()。在这里,您可以看到一个示例,可以帮助您实现这一目标:how do I collect a loop through a list from http in JSON


编辑:根据我在Update 2中看到的内容,JSON似乎格式错误,它需要在键和字符串值上加上引号。您可以使用它来尝试正确构建JSON:JSON Editor Online

我假设您要拥有的JSON结构是这样的:

{
  "places": [
    {
      "id": 4,
      "place_name": "The Oasis",
      "phone": "123-123-1234",
      "street_address": "456 Fake St",
      "place_logo": "https://restaurant.s3.amazonaws.com/restaurant_logo/restaurantLogo_jXon4qm.jpg",
      "place_photo": "https://restaurant.s3.amazonaws.com/restaurant_photo/farma.jpg",
      "city": "New York",
      "state": "New York",
      "zip_Code": 12345,
      "lat": 40,
      "lng": 40,
      "latlng": "(40.7770112244898, -74.2110798163265)",
      "opening_hours": [],
      "ratings": 3
    }
  ]
}

然后,要解析此JSON,您可以执行以下操作:

final String jsonExample = '{"places":[{"id":4,"place_name":"The Oasis","phone":"123-123-1234","street_address":"456 Fake St","place_logo":"https://restaurant.s3.amazonaws.com/restaurant_logo/restaurantLogo_jXon4qm.jpg","place_photo":"https://restaurant.s3.amazonaws.com/restaurant_photo/farma.jpg","city":"New York","state":"New York","zip_Code":12345,"lat":40,"lng":40,"latlng":"(40.7770112244898, -74.2110798163265)","opening_hours":[],"ratings":3}]}';

void testExample() {
  final responseData = json.decode(jsonExample);
  PlaceResults placeResults = PlaceResults.fromJSON(responseData);
  print('$placeResults');
}

class PlaceResults {
  List<Place> results;

  PlaceResults({this.results});

  factory PlaceResults.fromJSON(Map<String, dynamic> json) {
    List<Place> tempResults = [];

    for (int i = 0; i < json['places'].length; i++) {
      tempResults.add(Place.fromJSON(json['places'][i]));
    }

    return PlaceResults(results: tempResults);
  }

  @override
  String toString() {
    return results.fold("",(prev, element)=> '$element,$prev');
  }
}

class Place {
  int id;
  String placeName;
  String streetAddress;
  String city;
  String placePhoto;
  String state;
  num lat;
  num lng;
  num ratings;

  Place({
    this.id,
    this.streetAddress,
    this.city,
    this.placePhoto,
    this.lat,
    this.lng,
    this.placeName,
    this.state,
    this.ratings,
  });

  factory Place.fromJSON(Map<String, dynamic> json) {
    return Place(
      id: json['id'],
      placeName: json['place_name'],
      streetAddress: json['street_address'],
      city: json['city'],
      placePhoto: json['place_photo'],
      state: json['state'],
      lat: json['lat'],
      lng: json['lng'],
      ratings: json['ratings'],
    );
  }

  @override
  String toString() {
    return 'id:$id,placeName:$placeName,streetAddress:$streetAddress,city:$city,placePhoto:$placePhoto,state:$state,lat:$lat,lng:$lng,ratings:$ratings';
  }
}

注意:

  • 我使用的是num而非lat,lng和rating的double 因为在您的回复示例中它们是整数,但我认为他们可以 也要加倍,因此使用num可以接受两种情况
  • 我将Place类中的属性名称更改为 与响应的属性名称相同,以避免 困惑
  • 我将json ['id']之类的类型转换为int,因为它不是 必要
  • 我重写类中的toString()方法只是为了打印示例