adam.lofts
adam.lofts

Reputation: 1162

How to serialize list of polymorphic objects using built_value and StandardJsonPlugin?

Given a class hierarchy of animals like in the built_value polymorphism example:

Animal
    - Cat
    - Fish

I want to be able to (de)serialize a list of animals to JSON

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

I would like the type of animal to be encoded in each item. For example the json output could look like:

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

Upvotes: 2

Views: 1130

Answers (1)

David Morgan
David Morgan

Reputation: 486

Edit: this question/answer are now out of date; StandardJsonPlugin now supports polymorphism out of the box, as of version 4.5.0.

StandardJsonPlugin does not currently support polymorphism. According to the docs:

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

This issue, "Swagger / OpenAPI support", includes adding polymorphism support to StandardJsonPlugin:

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

One question: why do you need StandardJsonPlugin in the first place? If you stop using it, you have polymorphism support :)

Upvotes: 1

Related Questions