How to move several params to another node in jackson?

By | July 12, 2018
Questions:

I have to generate strange json from object(with jackson ObjectMapper), something like:

{
   "data":{
      "id":"1",
      "name":"Json"
   },
   "userType":"MD"
}

But, with jackson data-bind i can do only:

{
   "id":"1",
   "name":"Json",
   "userType":"MD"
}

With User.class:

public class User {
    private String id;
    private String name;
    private String userType;

//Getters Setters Constructor

I found two ways of bypassing. First one – to use another “superclass”:

public class Data {
    @JsonProperty("data")
    private User user;
    private String userType;
//Getters Setters Constructor

Second way – to use Map:

Map<String, Object> map = new HashMap<>();
        map.put("data", user);
        map.put("userType", "MD");
        String json = objMapper.writeValueAsString(map);

But i think, that it’s not idea to use this ways if i have about 8 different objects with such structure. So, what’s best pratice? Or maybe there are another built in ways?
I want to find the best one

Answers:

Leave a Reply

Your email address will not be published. Required fields are marked *