【问题标题】:How to (de-)serialize a list of objects?如何(反)序列化对象列表?
【发布时间】:2018-08-17 07:33:20
【问题描述】:

我找到了JSON serialization and deserialization to objects in Flutter 的示例,但是如何使用以下人员列表来做到这一点:

[
  {
    "name": "John",
    "age": 30,
    "cars": [
      {
        "name": "BMW",
        "models": [
          "320",
          "X3",
          "X5"
        ]
      }
    ]
  },
  {
    "name": "John",
    "age": 30,
    "cars": [
      {
        "name": "Ford",
        "models": [
          "Fiesta",
          "Focus",
          "Mustang"
        ]
      }
    ]
  }
]

当我打电话给_person = serializers.deserializeWith(Person.serializer, JSON.decode(json)); 时,我收到了这个错误:

The following _CastError was thrown attaching to the render tree:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' in type cast where
  _InternalLinkedHashMap is from dart:collection
  String is from dart:core
  String is from dart:core

我创建了一个环绕Persons 的类:

abstract class Persons implements Built<Persons, PersonsBuilder> {
  BuiltList<Person> get persons;

  Persons._();

  factory Persons([updates(PersonsBuilder b)]) = _$Persons;

  static Serializer<Persons> get serializer => _$personsSerializer;
}

并调用_person = serializers.deserializeWith(Persons.serializer, JSON.decode(json));,但错误是一样的。

如何(反)序列化 Json 对象列表?

【问题讨论】:

  • Person 类的外观如何?
  • @GünterZöchbauer 和这里一样:stackoverflow.com/a/44601296/1016472
  • 这看起来对built_value 非常具体。也许问他们的回购?
  • 您需要单独反序列化每个列表(顶级)条目。你注册了标准的 JSON 序列化插件吗?

标签: json dart


【解决方案1】:

代替

_person = serializers.deserializeWith(Person.serializer, JSON.decode(json));

试试

_person = serializers.deserializeWith(Person.serializer, (JSON.decode(json) as List).first);

或者

var personList = (JSON.decode(json) as List).map((j) =&gt; serializers.deserializeWith(Person.serializer, j)).toList();

【讨论】:

    猜你喜欢
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 2019-10-25
    • 2020-10-31
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多