【问题标题】:built_value deserialize got error " type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>' in type cast"built_value 反序列化出现错误“类型 '_InternalLinkedHashMap<String, dynamic>' 不是类型转换中类型 'Iterable<dynamic>' 的子类型”
【发布时间】:2018-07-27 12:55:16
【问题描述】:

我的模特:

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

错误:

发生了异常。 将“{userId: 1, id: 3, title: ea Molestias quasi exercitationem repellat qui ipsa ...”反序列化为“Post”失败,原因是:类型“_InternalLinkedHashMap”不是类型转换中“Iterable”类型的子类型

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

【问题讨论】:

    标签: dart flutter json-deserialization


    【解决方案1】:

    密钥是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 时,它也对我有用。

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 2019-03-14
      • 2021-06-19
      • 2020-11-25
      • 1970-01-01
      • 2019-09-19
      • 2019-08-28
      • 2020-03-03
      • 2021-11-06
      相关资源
      最近更新 更多