如何使用构建值构建列表



我有这个问题:

我有一个数组:

[
{
"name": "John",
},
{
"name": "Antonio",
},
{
"name": "Simon",
}
]

我使用built_value,如下所示,我试图反序列化json字符串:

library name;
import 'dart:convert';
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
part 'name.g.dart';
abstract class Name implements Built<Name, NameBuilder> {
String get name;
Name._();
factory Name([updates(NameBuilder b)]) = _$Name;
String toJson() {
return json.encode(serializers.serializeWith(Name.serializer, this));
}
static Name fromJson(String jsonString) {
return serializers.deserializeWith(
Name.serializer, json.decode(jsonString));
}
static Serializer<Name> get serializer => _$nameSerializer;
}

据我所知,我会得到这个名字,但我如何从中得到NameResult列表?

现在我试着这样做:

library name_result;
import 'dart:convert';
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
part 'name_result.g.dart';
abstract class NameResult implements Built<NameResult, NameResultBuilder> {
BuiltList<Name> get nameResult;
NameResult._();
factory NameResult([updates(NameResultBuilder b)]) = _$NameResult;
String toJson() {
return json.encode(serializers.serializeWith(NameResult.serializer, this));
}
static NameResult fromJson(String jsonString) {
return serializers.deserializeWith(
NameResult.serializer, json.decode(jsonString));
}
static Serializer<NameResult> get serializer => _$nameResultSerializer;
}

但我得到以下错误:failed due to: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' in type cast occurred in Instance of 'NameBloc'.

我该如何解决这个问题?

serializers.dart:

const builtListString = FullType(
BuiltList,
[FullType(String)],
);
...
final standardSerializers = (serializers.toBuilder()
..addBuilderFactory(
builtListString,
() => ListBuilder<String>(),
)
..add(Iso8601DateTimeSerializer())
..addPlugin(StandardJsonPlugin()))
.build();
final json = jsonDecode('[{ ... }]');
final names = standardSerializers.deserialize(
json,
specifiedType: builtListString,
) as BuiltList<String>;

相关内容

  • 没有找到相关文章

最新更新