gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:04:42 37 4
gpt4 key购买 nike

我找到了 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 = 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();

关于json - 如何(反)序列化对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49181724/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com