Reputation: 767
In built_value's official example show how to setup an array member of an object:
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._();
}
it just demonstrate how to deserialize a map but not array, the array just a key/member not the data itself.
but in may case, my http response is an array itself, not play as a member of the response.
my model:
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._();
}
my request is:
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');
}
}
response.body:
[
{'userId': 1, 'title': 'title1'},
{'userId': 2, 'title': 'title2'}
]
I looked up every tutorial or network discussion, no one mentions this scenario, or should I can only iterate the response.body
and deserialize to object one by one? for example:
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');
}
}
Upvotes: 1
Views: 1374