Flutter 解析具有多个对象类型的JSON数组
假设我有一个JSON数组,如下所示:Flutter 解析具有多个对象类型的JSON数组,flutter,dart,Flutter,Dart,假设我有一个JSON数组,如下所示: "videos": [ { "id": 25182, "game": 115653, "name": "Trailer", "video_id": "BdA22Lh6Rwk" }, 27749, { "id": 29188, "game": 115653, "name": "A New Team an
"videos": [
{
"id": 25182,
"game": 115653,
"name": "Trailer",
"video_id": "BdA22Lh6Rwk"
},
27749,
{
"id": 29188,
"game": 115653,
"name": "A New Team and New Rivals in Pokémon Sword and Pokémon Shield! ⚔️You have to know the different formats and figure out which one each entry is.
You can do that by checking the type of the entry: Is it an integer or a map?
Example:
List<Video> videosFromJson(List<Object> videoJson) {
var result = <Video>[];
for (int i = 0; i < videoJson.length; i++) {
var entry = videoJson[i];
if (entry is Map<String, dynamic>) {
result.add(Video.fromJson(entry));
} else if (entry is int) {
result.add(Video()..id = entry);
} else {
throw FormatException("Not a recognized video format", entry, i);
}
}
return result;
}
视频:[
{
识别号码:25182,
游戏编号:115653,
名称:拖车,
视频识别码:BdA22Lh6Rwk
},
27749,
{
身份证号码:29188,
游戏编号:115653,
名称:神奇宝贝宝剑和神奇宝贝盾的新团队和新对手!⚔️ 您必须了解不同的格式,并确定每个条目是哪一种格式。
您可以通过检查条目的类型来实现这一点:它是整数还是映射
例如:
你是说最后一行中的视频[1]吗?不建议使用你现在使用的JSON格式。你应该有数组的同构子级。@Malvindersingh是的,我是说视频[1],我的错。我知道这不是一种推荐的使用JSON格式的方法,但不幸的是,更改响应的JSON格式不是我能控制的:它可以工作!感谢您提供的易于理解的解释。