3

I found an example of JSON serialization and deserialization to objects in Flutter but how to do that with a list of persons like:

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

When I call _person = serializers.deserializeWith(Person.serializer, JSON.decode(json)); I get this error:

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

I created a surrounding Persons class:

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

  Persons._();

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

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

and call _person = serializers.deserializeWith(Persons.serializer, JSON.decode(json)); but the error is the same.

How to (de-)serialize a Json list of objects?

Ralph Bergmann
  • 3,015
  • 4
  • 30
  • 61

1 Answers1

0

Instead of

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

Try

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

Or

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

Kevin Moore
  • 5,921
  • 2
  • 29
  • 43