我正在尝试在Flutter中解析JSON数据,并且工作正常。但是,当某些数据为空或为null时,它将无法正常工作并显示错误。
import 'dart:convert';
GetFollowing getFollowingFromJson(String str) => GetFollowing.fromJson(json.decode(str));
class GetFollowing {
List<Content> content;
int count;
bool success;
String error;
GetFollowing({
this.error,
this.content,
this.count,
this.success,
});
factory GetFollowing.fromJson(Map<String, dynamic> json) => GetFollowing(
error: json["error"],
content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
count: json["count"],
success: json["success"],
);
}
class Content {
int uid;
int following;
String name;
String profilePhoto;
String baseLocation;
String registrationDate;
String country;
Content({
this.uid,
this.following,
this.name,
this.profilePhoto,
this.baseLocation,
this.registrationDate,
this.country,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
uid: json["uid"] ?? null,
following: json["following"] ?? null,
name: json["name"] ?? null,
profilePhoto: json["profile_photo"] ?? null,
baseLocation: json["base_location"] ?? null,
registrationDate: json["registration_date"] ?? null,
country: json["country"] ?? null,
);
}
这里是样本数据。
场景
{“错误”:“未找到记录。”,“成功”:false}
场景
{
"content": [{
"uid": 34,
"following": 35,
"name": "Sadi",
"profile_photo": "noimage.png",
"base_location": "New Delhi",
"registration_date": "03-05-2020",
"country": "India"
}, {
"uid": 34,
"following": 37,
"name": "Sameer",
"profile_photo": "noimage.png",
"base_location": "New Delhi",
"registration_date": "03-05-2020",
"country": "India"
}, {
"uid": 34,
"following": 36,
"name": "Simran",
"profile_photo": "noimage.png",
"base_location": "New Delhi",
"registration_date": "03-05-2020",
"country": "India"
}],
"count": 3,
"success": true
}
如果内容为null或为空,则解析出错,解析失败并给出错误。
Exception Caught: NoSuchMethodError: The method '[]' was called on null.
content: (json["content"] as List).map((x as Map<String, dynamic>) => Content.fromJson(x)).toList()
考虑json_annotation或built_value为您处理所有样板。