在built_value的官方example显示如何设置对象的数组成员:
abstract class Collections implements Built<Collections, CollectionsBuilder> {
static Serializer<Collections> get serializer => _$collectionsSerializer;
BuiltList<int> get list;
BuiltMap<String, int> get map;
BuiltListMultimap<int, bool> get listMultimap;
factory Collections([updates(CollectionsBuilder b)]) = _$Collections;
Collections._();
}
它只是演示如何反序列化映射而不是数组,数组只是一个键/成员而不是数据本身。
但在某些情况下,我的 http 响应本身就是一个数组,而不是响应的成员。
我的模型:
abstract class Post implements Built<Post, PostBuilder> {
static Serializer<Post> get serializer => _$postSerializer;
int get userId;
String get title;
factory Post([updates(PostBuilder b)]) = _$Post;
Post._();
}
我的要求是:
static Future<List<Post>> getPosts() async {
final response = await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
return serializers.deserialize(
json.decode(response.body),
specifiedType: FullType(Post)
);
} else {
throw Exception('Failed to load post');
}
}
响应主体:
[
{'userId': 1, 'title': 'title1'},
{'userId': 2, 'title': 'title2'}
]
我查了所有的教程或者网络讨论,都没有提到这个场景,还是只能迭代response.body
,一个一个反序列化成对象?例如:
static Future<List<Post>> getPosts() async {
final response = await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
final List<dynamic> data = json.decode(response.body);
return data.map((m){
return serializers.deserializeWith(Post.serializer, m);
}).toList();
} else {
throw Exception('Failed to load post');
}
}
最佳答案
根据@David Morgan 的 reply , built_value 还不支持反序列化列表。
Currently there’s no equivalent to deserializeWith for a list. You’ll need to deserialize one by one.
关于json - built_value 如何将 json 数组反序列化为对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51721663/