我正在尝试将JSON数据序列化为手动创建的对象。每当我尝试访问数据时,都会得到一个空值,但是,如果我打印序列化数据的长度,就会被告知我数组中有8个项目。我目前正在使用json_annotation:^ 2.0.0和json_serializable:作为项目中的依赖项。
这是我到目前为止尝试过的代码:
我的对象
class Restaurant {
int id;
String name;
String address;
String city;
String restaurantPhoto;
String state;
double lat;
double long;
String rating;
Restaurant({
this.id,
this.address,
this.city,
this.restaurantPhoto,
this.lat,
this.long,
this.name,
this.state,
this.rating,
});
factory RestaurantPhoto.fromJSON(Map<String, dynamic> json){
return Restaurant(
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,
);
}
}
这是我的方法:
Future getRestaurants() async {
var url = 'http://restaurant-8821.herokuapp.com/api/customer/restaurant/';
http.get(url, headers: {
"Content-Type": "application/x-www-form-urlencoded"
}).then((http.Response response) {
// print(response.body);
Map<String, dynamic> responseData = json.decode(response.body);
Restaurant restaurant = Restaurant.fromJSON(responseData);
print(responseData);
print(restaurant.name);
print(restaurant().length);
});
}
该方法将打印三个项目,并打印responseData:
{restaurant: [{id: 4, restaurant_name: The Oasis, phone: 123-123-1234, street_address: 456 Fake St, restaurant_logo: https://restaurant.s3.amazonaws.com/restaurant_logo/restaurantLogo_jXon4qm.jpg, restaurant_photo: https://restaurant.s3.amazonaws.com/restaurant_photo/farmas.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},
餐厅名称显示为空,并且restaurant.string.length输出12。
答案 0 :(得分:0)
我注意到您输入了反引号而不是引号
name: json[‘restaurant_name'] as String,
尝试
name: json['restaurant_name'] as String,