Search code examples
springjacksonjackson-databindjackson2

Query about flattening a nested json using Jackson


I've a json

{
    "parentId": "123",
    "parentName": "abc",
    "child": {
        "childId": "456",
        "childName": "xyz",
    }  
}

My requirement is to flatten the json so that I can map it to a pojo

class MyJson{
     private String parentId;
     private String parentName;
     private String childId;

    @JsonCreator
    public MyJson(@JsonProperty("parentId"),@JsonProperty("parentName"),
                      @JsonProperty("childId")){
        this.parentId = parentId;
        this.parentName = parentName;
        this.childId = childId;
    }
}

I know I can always create another pojo for Child Object, but I was wondering is there a way to directly map the nested child attribute to the pojo?


Solution

  • child is a JSON Object and you need to declare it as a Map:

    class MyJson {
        private String parentId;
        private String parentName;
        private String childId;
    
        @JsonCreator
        public MyJson(@JsonProperty("parentId") String parentId,
                      @JsonProperty("parentName") String parentName,
                      @JsonProperty("child") Map<String, String> child) {
            this.parentId = parentId;
            this.parentName = parentName;
            this.childId = child.get("childId");
        }
    }