I have a Java class like this and want to convert to JSON using Jackson. Thanks for your help.
public class myClass {
String Id;
Map<String, Object> optionalData = new LinkedHashMap<String, Object>();
}
For example, suppose the optionalData
is a Map saving two entries <"type", "book">
and <"year", "2014">
I want the output to be as follow. Please note that the key/value of optionalData could be changed on the fly (so, I cannot create a "static" Java object for this without using Map)
[
{
id: "book-id1",
type: "book",
year: "2014"
},
{
id: "book-id2",
type: "book",
year: "2013"
}
]
You can use the @JsonAnyGetter
annotation on a getter method that returns the map of optional values. Please refer to this blog plost that explains that in details.
Here is an example:
public class JacksonAnyGetter {
public static class myClass {
final String Id;
private final Map<String, Object> optionalData = new LinkedHashMap<>();
public myClass(String id, String key1, Object value1, String key2, Object value2) {
Id = id;
optionalData.put(key1, value1);
optionalData.put(key2, value2);
}
public String getid() {
return Id;
}
@JsonAnyGetter
public Map<String, Object> getOptionalData() {
return optionalData;
}
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
List<myClass> objects = Arrays.asList(
new myClass("book-id1", "type", "book", "year", 2013),
new myClass("book-id2", "type", "book", "year", 2014)
);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(objects));
}
}
Output:
[ {
"id" : "book-id1",
"type" : "book",
"year" : 2013
}, {
"id" : "book-id2",
"type" : "book",
"year" : 2014
} ]
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