I am using Genson to serialize a Java class into JSON. One of the class members is a Map, which I need to serialize directly into name/value pairs. For example:
public class Demo {
String name;
Map<String, String> mp = new HashMap<>();
...
name = "MyName";
mp.put("Book", "My book title");
mp.put("Fruit", "Orange");
...
}
Serialized I need:
{
"name":"Myname",
"Book": "My book title",
"Fruit": "Orange"
}
I tried to apply Genson, and I am getting close with its default operation, the output is:
{
"name":"Myname",
"mp":{
"Book": "My book title",
"Fruit": "Orange"
}
}
The keys in mp are guaranteed not to name-clash with any members of Demo.
How can this use-case by implemented with Genson?
It is possible to achieve this output by implementing a custom
Converter.For example:
Now,
Gensonshould be instantiated and used with this converter:More doc, in "Custom Converter" section.