0

This question's answer (Convert JSON many objects to single JSON using Jackson) explains how to flatten JSON using Jackson

But my json is like this

{
  "field1":"value1",
  "field2":"value2",
  "field3": {
     "type":{
        "f1":"v1",
        "f2":"v2"
     }
  }
}  

I need something like this

{
  "field1":"value1",
  "field2":"value2",
  "field3": {
        "f1":"v1",
        "f2":"v2"
  }
}  

so that field3.type is put directly into field3 and then deserialize to Json object

I need steps to do this just using jackson annotations and not by unpacking the nested object.

gls79
  • 1

1 Answers1

0

Use the @JsonCreator annotation for the constructor of field3:

public class Flattened implements Serializable {

    static ObjectMapper objectMapper = new ObjectMapper();
    
    public String field1;
    public String field2;
    public Field3Class field3;
    
    public static void main(String[] args) throws IOException {

        String jsonSerialised = "{\r\n" + 
                "  \"field1\":\"value1\",\r\n" + 
                "  \"field2\":\"value2\",\r\n" + 
                "  \"field3\": {\r\n" + 
                "     \"type\":{\r\n" + 
                "        \"f1\":\"v1\",\r\n" + 
                "        \"f2\":\"v2\"\r\n" + 
                "     }\r\n" + 
                "  }\r\n" + 
                "}  ";
        
        Flattened flattenedValue = objectMapper.readValue(jsonSerialised, Flattened.class);
        objectMapper.writeValue(System.out, flattenedValue);
    }
    
    public static class Field3Class implements Serializable {
        public String f1;
        public String f2;
        @JsonCreator
        public Field3Class(@JsonProperty("type") Type type) {
            this.f1 = type.f1;
            this.f2 = type.f2;
        }
        
        public static class Type implements Serializable {
            public String f1;
            public String f2;
       }
    }
}

Output:

{"field1":"value1","field2":"value2","field3":{"f1":"v1","f2":"v2"}}
John Williams
  • 4,252
  • 2
  • 9
  • 18