1

我所有的 JSON 数据都包含状态(int)、msg(字符串)和数据(任何类型)。因为我来自java,所以我想使用泛型。我正在为带有built_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.
4

1 回答 1

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

有用。

于 2019-03-31T01:41:35.007 回答