1

What would be the best way to serialize/deserialize instances of MyClass using Jackson?

class MyClass {
    private String name;
    private MyInterface classInstance;

    // standard getters setters
}

Attribute classInstance can be of an arbitrary type which implements interface MyInterface

Ideally I'd like the yaml structure to look like this

name: com.example.ClassE
classInstance: 
  value: 42
  category: "fancy"

Notice that the "name" attribute actually contains a fully qualified type of the object inside "classInstance" attribute.

Jakub Smolar
  • 81
  • 10

1 Answers1

2

Check JsonTypeInfo annotation. It can generate class property for you and deserialise YAML payload using this property. Check below example:

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;

import java.math.BigDecimal;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        YAMLFactory yamlFactory = new YAMLFactory();
        yamlFactory.disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID);

        ObjectMapper mapper = new ObjectMapper(yamlFactory);

        serialiseAndDeserialise(mapper, new MyValue());
        serialiseAndDeserialise(mapper, new MyBigDecimal());
    }

    private static void serialiseAndDeserialise(ObjectMapper mapper, MyInterface myInterface) throws java.io.IOException {
        MyClass myClass = new MyClass();
        myClass.setInstance(myInterface);

        String yaml = mapper.writeValueAsString(myClass);
        System.out.println(yaml);
        System.out.println(mapper.readValue(yaml, MyClass.class));
    }
}

class MyClass {

    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "name")
    private MyInterface instance;

    public MyInterface getInstance() {
        return instance;
    }

    public void setInstance(MyInterface instance) {
        this.instance = instance;
    }

    @Override
    public String toString() {
        return "MyClass{" +
                "instance=" + instance +
                '}';
    }
}

interface MyInterface {
}

class MyValue implements MyInterface {
    private int value = 42;
    private String category = "fancy";

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    @Override
    public String toString() {
        return "MyValue{" +
                "value=" + value +
                ", category='" + category + '\'' +
                '}';
    }
}

class MyBigDecimal implements MyInterface {
    private BigDecimal pi = BigDecimal.valueOf(Math.PI);

    public BigDecimal getPi() {
        return pi;
    }

    public void setPi(BigDecimal pi) {
        this.pi = pi;
    }

    @Override
    public String toString() {
        return "MyBigDecimal{" +
                "pi=" + pi +
                '}';
    }
}

Above code prints:

---
instance:
  name: "com.celoxity.MyValue"
  value: 42
  category: "fancy"

MyClass{instance=MyValue{value=42, category='fancy'}}
---
instance:
  name: "com.celoxity.MyBigDecimal"
  pi: 3.141592653589793

MyClass{instance=MyBigDecimal{pi=3.141592653589793}}

If you want to move name on the same level as instance change only annotation to:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "name")

And output will change to:

---
instance:
  value: 42
  category: "fancy"
name: "com.celoxity.MyValue"

MyClass{instance=MyValue{value=42, category='fancy'}}
---
instance:
  pi: 3.141592653589793
name: "com.celoxity.MyBigDecimal"

MyClass{instance=MyBigDecimal{pi=3.141592653589793}}

I prefer first one, because it informs that name property belongs to instance. If you remove name property from annotation Jackson will use default name for this kind of use - '@class'.

See also:

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146