gpt4 book ai didi

dart - build_value可以反序列化这样的泛型吗?

转载 作者:行者123 更新时间:2023-12-03 03:41:18 39 4
gpt4 key购买 nike

我所有的JSON数据都包含status(int),msg(String)和data(任何类型)。因为我来自Java,所以我想使用泛型。我正在为具有build_value的顶级泛型编写反序列化,但是失败了。

我尝试了这个

https://github.com/google/built_value.dart/blob/master/end_to_end_test/test/generics_serializer_test.dart

但是不是很明白。

以下是我的代码:

 abstract class GenericValue<T>
implements Built<GenericValue<T>, GenericValueBuilder<T>> {
T get data;

int get status;

String get msg;

GenericValue._();


static Serializer<GenericValue> get serializer => _$genericValueSerializer;

factory GenericValue([updates(GenericValueBuilder<T> b)]) =
_$GenericValue<T>;
}




abstract class UserInfo implements Built<UserInfo, UserInfoBuilder> {
static Serializer<UserInfo> get serializer => _$userInfoSerializer;

String get id;

String get email;

UserInfo._();

factory UserInfo([updates(UserInfoBuilder b)]) = _$UserInfo;
}

GenericValue<UserInfo> parseUserInfo(String jsonStr) {
final parsed = json.jsonDecode(jsonStr);
final specifiedType = const FullType(GenericValue, [FullType(UserInfo)]);
final serializersWithBuilder = (standardSerializers.toBuilder()
..addBuilderFac`enter code here`tory(specifiedType, () => GenericValueBuilder<UserInfo>
()))
.build();
Response<UserInfo> response = serializersWithBuilder.deserialize(parsed,
specifiedType: specifiedType);
return response;
}

but result is: Invalid argument(s): Unknown type on deserialization. Need either specifiedType or discriminator field.


how can it do it in right way, to deserialize JSON data like this.

最佳答案

 String toJsonUserInfo() {
final specifiedType = const FullType(GenericValue, [FullType(UserInfo)]);
final serializersWithBuilder = (standardSerializers.toBuilder()
..addBuilderFactory(
specifiedType, () => GenericValueBuilder<UserInfo>()))
.build();
return json.encode(
serializersWithBuilder.serialize(this, specifiedType: specifiedType));
}

static GenericValue<UserInfo> fromJsonUserInfo(String jsonString) {
final specifiedType = const FullType(GenericValue, [FullType(UserInfo)]);
final serializersWithBuilder = (standardSerializers.toBuilder()
..addBuilderFactory(
specifiedType, () => GenericValueBuilder<UserInfo>()))
.build();
return serializersWithBuilder.deserialize(json.decode(jsonString),
specifiedType: specifiedType);
}

有用。

关于dart - build_value可以反序列化这样的泛型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55426971/

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