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:
import com.owlike.genson.Context;
import com.owlike.genson.Converter;
import com.owlike.genson.stream.ObjectReader;
import com.owlike.genson.stream.ObjectWriter;
public class DemoConverter implements Converter<Demo> {
@Override
public void serialize(Demo demo, ObjectWriter objectWriter, Context context) {
objectWriter.beginObject();
objectWriter.writeString("name", demo.getName());
demo.getMp().forEach((prop, value) ->
objectWriter.writeString(prop, value)
);
objectWriter.endObject();
}
@Override
public Demo deserialize(ObjectReader objectReader, Context context) throws Exception {
// TODO
}
}
Now, Genson
should be instantiated and used with this converter:
Genson genson = new GensonBuilder().withConverters(new DemoConverter()).create();
String json = genson.serialize(demo);
// and the JSON is
{"name":"MyName","Fruit":"Orange","Book":"My book title"}