如何(取消)序列化对象列表?

时间:2018-03-08 20:15:38

标签: json dart

我找到了一个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对象列表?

1 个答案:

答案 0 :(得分:0)

而不是

_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) => serializers.deserializeWith(Person.serializer, j)).toList();