如何使用built_value和StandardJsonPlugin序列化多态对象列表?

时间:2017-12-06 12:22:13

标签: dart

给出built_value polymorphism example中的动物类层次结构:

Animal
    - Cat
    - Fish

我希望能够(de)将动物列表序列化为JSON

class Zoo implements Built<Zoo, ZooBuilder>  {
    static Serializer<Zoo> get serializer => _$zooSerializer;
    BuiltList<Animal> animals;
}

我想在每个项目中编码动物的类型。例如,json输出可能如下所示:

{
"animals": [
    {"type": "cat", "legs": 2},
    {"type": "fish", "fins": 3}
]}

1 个答案:

答案 0 :(得分:1)

编辑:这个问题/答案现在已经过时了;从版本4.5.0开始,StandardJsonPlugin现在支持开箱即用的多态性。

StandardJsonPlugin目前不支持多态性。根据文件:

/// The default serialization format is more powerful, supporting polymorphism
/// and more collection types.

此问题“Swagger / OpenAPI支持”包括向StandardJsonPlugin添加多态支持:

https://github.com/google/built_value.dart/issues/92

一个问题:为什么你首先需要StandardJsonPlugin?如果您停止使用它,您将获得多态支持:)

相关问题