0

I am building an application for payara-micro. I need to convert a Json string to an object that extends a super class. The problem that I have is that both the parent and the child's fields are not populated and the instance created is not of type sub-class:

E.g. Person has a list of Vehicle (subtypes: Bike, Bus,...)

  {
      name: "John",
      vehicles: [
          {
              type: "bike",
              doors: 5
          }
      ]
  }

The resulting object of this json will be a Person object with name populated, and a list of Vehicle with one element but the type of that element will be Vehicle and no fields in Vehicle will have a value.

Jsonb jsonb = JsonbBuilder.create();
Person person = jsonb.fromJson(jsonString, Person.class);
FourtyTwo
  • 734
  • 8
  • 19

1 Answers1

1

Unfortunately, the functionality you're looking for is not part of Yasson (nor JSON-B). The specification doesn't explicitly mention this, but the User Guide on Serializers/Deserializers hints at it (emphasis mine):

Let’s take a look at the sample. Imagine that we would like to serialize and deserialize a list of pet carriers. A carried pet defined by an abstract class Animal. It can be any of its subclasses. We would like to properly serialize and deserialize it. In order to do it we need to preserve a type information in JSON document and use it on deserialization. It can be done using custom serializer/deserializer pair.

The example contains a custom serializer/deserializer, which should get you the desired result, but you will have to implement this custom serializer/deserializer yourself.

Martijn
  • 5,491
  • 4
  • 33
  • 41