I am serialising an object, which I’d like to put a root value for.
This is my class.
@JsonRootName(value = "user") public class User { @JsonProperty private String name; @JsonProperty private int id; public User(int id, String name) { this.name = name; this.id = id; } }
This is how I am serialising it:
public static void main(String[] args) throws JsonProcessingException { User user = new User(1, "foobar"); ObjectMapper mapper = new ObjectMapper(); String serilizedValue = mapper.writeValueAsString(user); System.out.println(serilizedValue); }
But the serialised value is:
{"name":"foobar","id":1}
While I was hopping to have a root json value as fed in the class definition.
Could you help with that please?
Advertisement
Answer
@JsonRootName(value = "user") public static class User { @JsonProperty private String name; @JsonProperty private int id; public User(int id, String name) { this.name = name; this.id = id; } } public static void main(String[] args) throws InterruptedException, ParseException, JsonProcessingException { User user = new User(1, "foobar"); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); String serilizedValue = mapper.writeValueAsString(user); System.out.println(serilizedValue); }
Output:
{"user":{"name":"foobar","id":1}}
You need to enable WRAP_ROOT_VALUE
on the object mapper