I have a bean like this
class Foo {
private Map<String, Data> dataMap;
private String fooFieldOne;
private String fooFieldTwo;
}
class Data {
private fieldOne;
private fieldTwo;
}
I want to serialize as Json as like this
{
"key1": {
"fieldOne": "some value",
"fieldTwo": "some value"
},
"key2": {
"fieldOne": "some other value",
"fieldTwo": "some other value"
},
"fooFieldOne":"valueone",
"fooFieldTwo":"valuetwo"
}
But i am getting result like
{
"dataMap": {
"key1": {
"fieldOne": "some value",
"fieldTwo": "some value"
},
"key2": {
"fieldOne": "some other value",
"fieldTwo": "some other value"
}
},
"fooFieldOne":"valueone",
"fooFieldTwo":"valuetwo"
}
How to ignore dataMap layer in the above json? I'm using java jackson library for this.
Code i tried is
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(myFOOObject)
We are using writeObject() method of ObjectOutputStream to serialize HashMap in Java. In the following program, we save the hashmap content in a serialized newHashMap file. Once you run the following code, a newHashMap file will be created. This file is used for deserialization in the next upcoming program.
ObjectMapper is Jackson's serialization mapper. It allows us to serialize our map, and write it out as a pretty-printed JSON String using the toString() method in String: { "key" : "value" }
Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.
Jackson can serialize and deserialize polymorphic data structures very easily. The CarTransporter can itself carry another CarTransporter as a vehicle: that's where the tree structure is! Now, you know how to configure Jackson to serialize and deserialize objects being represented by their interface.
You could create a getter for dataMap and serialize the dataMap instead of the entire Foo
instance.
mapper.writeValueAsString(myFOOObject.getDataMap());
Another method is using the @JsonUnwrapped
annotation. This annotation is available in Jackson 1.9+.
http://jackson.codehaus.org/1.9.9/javadoc/org/codehaus/jackson/annotate/JsonUnwrapped.html
The downside of using this annotation is the inability to use maps as stated in the answer to your other question
I found answer - using @JsonAnyGetter annotation with getter for map. To avoid conflicts during deserialization should be used @JsonAnySetter annotation with setter for this map.
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