Close

Jackson JSON - Using @JsonAnyGetter Annotation to serialize any arbitrary properties

[Updated: Aug 31, 2018, Created: Aug 31, 2018]

@JsonAnyGetter can be used on a method which returns a Map. The Map is persisted as flattened properties of the target POJO. This annotation functionality is similar to @JsonWrapped, but @JsonAnyGetter can be used to persist any arbitrary properties rather than nested properties.

Example

POJO

public class ScreenInfo {
    private String id;
    private String title;
    private int width;
    private int height;
    private Map<String, Object> otherInfo;
    ....

    public void addOtherInfo(String key, Object value) {
        if (this.otherInfo == null) {
            this.otherInfo = new HashMap<>();
        }
        this.otherInfo.put(key, value);
    }

    @JsonAnyGetter
    public Map<String, Object> getOtherInfo() {
        return otherInfo;
    }

    ....
}

Serializing as JSON

public class MainScreenInfoSerialization {
  public static void main(String[] args) throws IOException {
      ScreenInfo si = new ScreenInfo();
      si.setId("TradeDetails");
      si.setTitle("Trade Details");
      si.setWidth(500);
      si.setHeight(300);
      si.addOtherInfo("xLocation", 400);
      si.addOtherInfo("yLocation", 200);

      System.out.println("-- before serialization --");
      System.out.println(si);

      ObjectMapper om = new ObjectMapper();
      String jsonString = om.writeValueAsString(si);
      System.out.println("-- after serialization --");
      System.out.println(jsonString);
  }
}
-- before serialization --
ScreenInfo{id='TradeDetails', title='Trade Details', width=500, height=300, otherInfo={xLocation=400, yLocation=200}}
-- after serialization --
{"id":"TradeDetails","title":"Trade Details","width":500,"height":300,"xLocation":400,"yLocation":200}

Without @JsonAnyGetter

In above example, if we remove @JsonAnyGetter from ScreenInfo#getOtherInfo() then output will be:

-- before serialization --
ScreenInfo{id='TradeDetails', title='Trade Details', width=500, height=300, otherInfo={xLocation=400, yLocation=200}}
-- after serialization --
{"id":"TradeDetails","title":"Trade Details","width":500,"height":300,"otherInfo":{"xLocation":400,"yLocation":200}}

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.6: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 10
  • Maven 3.5.4

@JsonAnyGetter Example Select All Download
  • jackson-json-any-getter-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ScreenInfo.java

    See Also