如何在flutter中反序列化json中的对象列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51053954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Deserialize a list of objects from json in flutter
提问by Gainz
I am using the dart package json_serializable for json serialization. Looking at the flutter documentation it shows how to deserialize a single object as follow:
我正在使用 dart 包 json_serializable 进行 json 序列化。查看 flutter 文档,它显示了如何反序列化单个对象,如下所示:
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
However, I am not familiar enough with dart to figure out how to do the same for a list of items instead of a single instance.
但是,我对 dart 不够熟悉,无法弄清楚如何对项目列表而不是单个实例执行相同的操作。
回答by Fallenreaper
Well, your service would handle either the response body being a map, or a list of maps accordingly. Based on the code you have, you are accounting for 1 item.
好吧,您的服务将相应地处理作为地图的响应正文或地图列表。根据您拥有的代码,您计算了 1 个项目。
If the response body is an iterable, then you need to parse and walk accordingly, if i am understanding your question correctly.
如果响应正文是可迭代的,那么如果我正确理解您的问题,则您需要相应地解析和行走。
Example:
例子:
Iterable l = json.decode(response.body);
List<Post> posts = List<Post>.from(l).map((Map model)=> Post.fromJson(model)).toList();
where posts is a LIST of posts.
其中posts 是一个帖子列表。
EDIT: I wanted to add a note of clarity here. The purpose here is that you decode the response returned. The next step, is to turn that iterable of json objects into an instance of your object. This is done by creating fromJson methods in your class to properly take json and implement it accordingly. Below is a sample implementation.
编辑:我想在这里添加一个清晰的注释。这里的目的是解码返回的响应。下一步是将 json 对象的可迭代对象转换为对象的实例。这是通过在您的类中创建 fromJson 方法以正确获取 json 并相应地实现它来完成的。下面是一个示例实现。
class Post {
// Other functions and properties relevant to the class
// ......
/// Json is a Map<dynamic,dynamic> if i recall correctly.
static fromJson(json): Post {
Post p = new Post()
p.name = ...
return p
}
}
I am a bit abstracted from Dart these days in favor of a better utility for the tasks needing accomplished. So my syntax is likely off just a little, but this is Pseudocode.
这些天我对 Dart 有点抽象,赞成为需要完成的任务提供更好的实用程序。所以我的语法可能有点偏差,但这是伪代码。
EditThere was a change in the API for this functionality at some point in the past. I do not program in Dart anymore so it is hard for me to test some of these updates. That being said, it looks like it is having issues casting now in this newer version of dart, and i updated the above answer. It takes the iterable and casts it to a List of Post, and then will conduct map on that List.
编辑在过去的某个时候,此功能的 API 发生了变化。我不再使用 Dart 编程,因此我很难测试其中的一些更新。话虽这么说,现在在这个较新版本的 dart 中似乎有问题,我更新了上面的答案。它接受可迭代对象并将其强制转换为 Post 列表,然后在该列表上进行映射。
回答by Bilal ?im?ek
I always use this way with no problem;
我总是用这种方式没有问题;
List<MyModel> myModels;
var response = await http.get("myUrl");
myModels=(json.decode(response.body) as List).map((i) =>
MyModel.fromJson(i)).toList();
回答by Developine
Just another example on JSON Parsing for further clarification.
另一个关于 JSON 解析的示例以供进一步说明。
Let say we want to parse items array in our JSON Object.
假设我们要解析 JSON 对象中的 items 数组。
factory YoutubeResponse.fromJSON(Map<String, dynamic> YoutubeResponseJson)
{
// Below 2 line code is parsing JSON Array of items in our JSON Object (YouttubeResponse)
var list = YoutubeResponseJson['items'] as List;
List<Item> itemsList = list.map((i) => Item.fromJSON(i)).toList();
return new YoutubeResponse(
kind: YoutubeResponseJson['kind'],
etag: YoutubeResponseJson['etag'],
nextPageToken: YoutubeResponseJson['nextPageToken'],
regionCode: YoutubeResponseJson['regionCode'],
mPageInfo: pageInfo.fromJSON(YoutubeResponseJson['pageInfo']),
// Here we are returning parsed JSON Array.
items: itemsList);
}
回答by Aks
You can also Do it like
你也可以这样做
List< Item > itemsList= List< Item >.from(parsedListJson.map((i) => Item.fromJson(i)));
回答by Nourein
First, create a class that matches your json data, in my case, I create (generate) class named Img:
首先,创建一个与您的 json 数据匹配的类,在我的情况下,我创建(生成)名为 的类Img:
import 'dart:convert';
Img imgFromJson(String str) => Img.fromJson(json.decode(str));
String imgToJson(Img data) => json.encode(data.toJson());
class Img {
String id;
String img;
dynamic decreption;
Img({
this.id,
this.img,
this.decreption,
});
factory Img.fromJson(Map<String, dynamic> json) => Img(
id: json["id"],
img: json["img"],
decreption: json["decreption"],
);
Map<String, dynamic> toJson() => {
"id": id,
"img": img,
"decreption": decreption,
};
}
PS. You can use app.quicktype.ioto generate your json data class in dart. then send you post/get to your server:
附注。您可以使用app.quicktype.io在 dart 中生成您的 json 数据类。然后将您发布/获取到您的服务器:
Future<List<Img>> _getimages() async {
var response = await http.get("http://192.168.115.2/flutter/get_images.php");
var rb = response.body;
// store json data into list
var list = json.decode(rb) as List;
// iterate over the list and map each object in list to Img by calling Img.fromJson
List<Img> imgs = list.map((i)=>Img.fromJson(i)).toList();
print(imgs.runtimeType); //returns List<Img>
print(imgs[0].runtimeType); //returns Img
return imgs;
}
for more info this is an article about Parsing complex JSON in Flutter
有关更多信息,这是一篇关于在 Flutter 中解析复杂 JSON的文章
回答by vinod yadav
follow this step
step 1-> create model class (name as LoginResponce ) click here to convert json to dart.
step 2-> LoginResponce loginResponce=LoginResponce.fromJson(json.decode(response.body));
按照此步骤
步骤 1-> 创建模型类(名称为 LoginResponce )单击此处将 json 转换为 dart。
步骤 2->LoginResponce loginResponce=LoginResponce.fromJson(json.decode(response.body));
step 3 -> now you get your data in instence of model (as loginResponce ).
第 3 步 -> 现在您可以在模型实例中获取数据(作为 loginResponce )。

