4

I know we can use Jackson MixIn's to rename a property or to ignore a property (see examples here). But is it possible to add a property?

The added property can be:

  1. A constant (such as a version number)
  2. A computed value (e.g. if the source class has properties for getWidth() and getHeight(), but we want to ignore both and export a getArea() instead)
  3. Flattened information from nested members (e.g. a class has a member Information which in turn has a member Description, and we want to have a new property for description and skipping the nesting structure of Information)
leeyuiwah
  • 6,562
  • 8
  • 41
  • 71

1 Answers1

4

From documentation:

"Mix-in" annotations are a way to associate annotations with classes, without modifying (target) classes themselves, originally intended to help support 3rd party datatypes where user can not modify sources to add annotations.

With mix-ins you can:
1. Define that annotations of a '''mix-in class''' (or interface)
2. will be used with a '''target class''' (or interface) such that it appears
3. as if the ''target class'' had all annotations that the ''mix-in'' class has (for purposes of configuring serialization / deserialization)

To solve your problems you can:

  • Create new POJO which has all required fields.
  • Implement custom serialiser.
  • Before serialisation convert POJO to Map and add/remove nodes.
  • Use com.fasterxml.jackson.databind.ser.BeanSerializerModifier to extend custom serialisers. See: Jackson custom serialization and deserialization.

For example, to add a constant version to each object you can wrap it in Verisoned class:

class Versioned {

    private final String version;

    @JsonUnwrapped
    private final Object pojo;

    public Versioned(String version, Object pojo) {
        this.version = version;
        this.pojo = pojo;
    }

    public String getVersion() {
        return version;
    }

    public Object getPojo() {
        return pojo;
    }
}

Now, if you wrap an Arae(width, height) object:

Area area = new Area(11, 12);
String json = mapper.writeValueAsString(new Versioned("1.1", area));

output will be:

{
  "version" : "1.1",
  "width" : 11,
  "height" : 12
}
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146