Suppose I have a pojo:
import org.codehaus.jackson.map.*; public class MyPojo { int id; public int getId() { return this.id; } public void setId(int id) { this.id = id; } public static void main(String[] args) throws Exception { MyPojo mp = new MyPojo(); mp.setId(4); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true); System.out.println(mapper.getSerializationConfig().isEnabled(SerializationConfig.Feature.WRAP_ROOT_VALUE)); System.out.println(mapper.writeValueAsString(mp)); } }
When I serialize using the Jackson ObjectMapper, I just get
true {"id":4}
but I want
true {"MyPojo":{"id":4}}
I've searched all over, Jacksons documentation is really unorganized and mostly out of date.
How to ignore parent tag from json?? String str = "{\"parent\": {\"a\":{\"id\": 10, \"name\":\"Foo\"}}}"; And here is the class to be mapped from json. (a) Annotate you class as below @JsonRootName(value = "parent") public class RootWrapper { (b) It will only work if and only if ObjectMapper is asked to wrap.
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.
But as far as @JsonProperty goes, no, the POJO classes do NOT need anything to mark them as serializable; nor do properties if you have public getter or setter.
By adding the jackson annotation @JsonTypeInfo
in class level you can have the expected output. i just added no-changes in your class.
package com.test.jackson; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; @JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME) public class MyPojo { // Remain same as you have }
output:
{ "MyPojo": { "id": 4 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With