Reputation: 767
my model:
abstract class Post implements Built<Post, PostBuilder> {
static Serializer<Post> get serializer => _$postSerializer;
int get userId;
int get id;
String get title;
String get body;
factory Post([updates(PostBuilder b)]) = _$Post;
Post._();
}
my reqest:
Future<Post> getPostById(int id) async {
final resp = await http.get('https://jsonplaceholder.typicode.com/posts/${id}');
if(resp.statusCode == 200) {
return serializers.deserializeWith(Post.serializer, json.decode(resp.body));
}else {
throw Exception('Failed to load post');
}
}
and the breakpoint in source code at:
if (serializer is StructuredSerializer) {
try {
// ===> HERE
return serializer.deserialize(this, object as Iterable,
specifiedType: specifiedType);
} on Error catch (error) {
throw new DeserializationError(object, specifiedType, error);
}
}else if(serializer is PrimitiveSerializer) {
//...
}
the Error:
Exception has occurred. Deserializing '{userId: 1, id: 3, title: ea molestias quasi exercitationem repellat qui ipsa...' to 'Post' failed due to: type '_InternalLinkedHashMap' is not a subtype of type 'Iterable' in type cast
my question is where I'm wrong with the type definition or deserialization usage, and, I got a single object in response.body(a Map), why the code exectue at as Iterable
but not PrimitiveSerializer
directive.
Upvotes: 1
Views: 2363
Reputation: 767
the key is StandardJsonPlugin
.
I copied the serializers.dart file from official example:
@SerializersFor(const [
Account,
Cat,
CompoundValue,
Fish,
GenericValue,
SimpleValue,
VerySimpleValue,
])
final Serializers serializers = _$serializers; // see this line
but when I look up in the network, people use this:
final Serializers serializers =
(
_$serializers.toBuilder()
..addPlugin(StandardJsonPlugin())
).build();
and sure it works for me either, when I add the StandardJsonPlugin
.
Upvotes: 6