Search code examples
javajacksonannotationsdeserialization

Jackson deserialize properties within nested JSON


I have a POJO that looks like this

class Bean {
    private Instant created;
    private Instant updated;
    private String name;
    private int count;
} 

and the input JSON data looks like this

{
  "time_created": <custom timestamp>,
  "time_updated": <custom timestamp>,
  // Other data...
  "person": {
    "name": "John"
    // Other data...
  },
  "stats": {
    "button": {
      "count": 5
      // ...
    }
    // ...
  }
}

I want to deserialize the JSON so that it's flattened into the POJO. Nesting classes feels like overkill as I just want a specific property, and I don't want to have calls like bean.getStats().getButton().getCount(), I just want bean.getCount(). I've done this already with a custom deserializer, but it's messy and brittle.

Is there a way to do this with annotations? Something like

@JsonProperty(name = "count", root = "stats/button")
private int count;

Additionally, the Instants need a custom deserializer. I believe I can cover that with

@JsonDeserialize(using = CustomInstantDeserializer.class)
private Instant created;
@JsonDeserialize(using = CustomInstantDeserializer.class)
private Instant updated;

as annotations on each of the fields.


Solution

  • Sorry to disappoint but as it seems it is an open issue in Jackson: https://github.com/FasterXML/jackson-annotations/issues/42 If you want you can upvote this issue and they might add it in the future, but for now you need to do it manually with a custom deserializer.