Home > OS >  Changing POJO structure on returning to API call
Changing POJO structure on returning to API call

Time:12-20

I have assigned values to my POJO class to return as response body to an API call. I want to change my POJO structure, like by making the POJO as value to an object on top of the POJO.

For example:

Home POJO:

{
    int number;
    String address;
}

Values are assigned to the POJO and I can send it as response body to my API call, but I want my response body to be:

{
  output: {
      number: 1,
      address: "chennai"
    }
}

I know that I can achieve this using JSON-Object or using a HashMap or a parent POJO (Note: I do not want to create a POJO Output just for this case).

Is there any other way to serialize the POJO like this using Jackson or any other methods for Java with Spring?

CodePudding user response:

You can apply @JsonRootName annotation on your class specifying "output" as its value.

@JsonRootName("output")
public class MyPojo {
    private int number;
    private String address;
    
    // all-args constructor, getters, etc.
}

But this annotation alone would not have any impact on serialization. In order to make to instruct Jackson to use it, we need to enable the serialization feature WRAP_ROOT_VALUE:

Feature that can be enabled to make root value (usually JSON Object but can be any type) wrapped within a single property JSON object, where key as the "root name", ...

Usage example:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
        
System.out.println(
    mapper
        .writerWithDefaultPrettyPrinter()
        .writeValueAsString(new MyPojo(1000, "foo"))
);

Output:

{
  "output" : {
    "number" : 1000,
    "address" : "foo"
  }
}
  • Related