' is not a subtype of type ' Iterable' in type cast"-6ren"> ' is not a subtype of type ' Iterable' in type cast"-我的模型: abstract class Post implements Built { static Serializer get serializer => _$postSerialize-6ren">
gpt4 book ai didi

dart - built_value 反序列化得到错误 "type ' _InternalLinkedHashMap' is not a subtype of type ' Iterable' in type cast"

转载 作者:IT王子 更新时间:2023-10-29 07:00:35 53 4
gpt4 key购买 nike

我的模型:

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._();
}

我的要求:

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');
}
}

源代码中的断点位于:

 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) {
//...
}

错误:

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

我的问题是我在类型定义或反序列化用法上哪里出错了,而且,我在 response.body(a Map) 中得到了一个对象,为什么代码在 as Iterable 处执行但是不是 PrimitiveSerializer 指令。

最佳答案

关键是StandardJsonPlugin

我从官方example复制了serializers.dart文件:

@SerializersFor(const [
Account,
Cat,
CompoundValue,
Fish,
GenericValue,
SimpleValue,
VerySimpleValue,
])
final Serializers serializers = _$serializers; // see this line

但是当我在网络中查找时,人们使用这个:

final Serializers serializers = 
(
_$serializers.toBuilder()
..addPlugin(StandardJsonPlugin())
).build();

当我添加 StandardJsonPlugin 时,确保它也适用于我。

关于dart - built_value 反序列化得到错误 "type ' _InternalLinkedHashMap<String, dynamic >' is not a subtype of type ' Iterable<dynamic >' in type cast",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51558430/

53 4 0