build_value是否可以像这样反序列化泛型?

时间:2019-03-30 00:18:14

标签: dart flutter built-value

我所有的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.

1 个答案:

答案 0 :(得分:0)

 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);
  }

有效。