我正在使用Genson将Java类序列化为JSON。类成员之一是Map,我需要直接将其序列化为名称/值对。例如:
public class Demo {
String name;
Map<String, String> mp = new HashMap<>();
...
name = "MyName";
mp.put("Book", "My book title");
mp.put("Fruit", "Orange");
...
}
序列化我需要:
{
"name":"Myname",
"Book": "My book title",
"Fruit": "Orange"
}
我尝试应用Genson,并且接近其默认操作,输出为:
{
"name":"Myname",
"mp":{
"Book": "My book title",
"Fruit": "Orange"
}
}
保证mp中的键不会与Demo的任何成员发生名称冲突。
如何用Genson来实现这个用例?
最佳答案
通过实现自定义Converter
可以实现此输出。
例如:
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
}
}
现在,应实例化
Genson
并与此转换器一起使用: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"}
More doc, in "Custom Converter" section。
关于java - 使用Genson将 map 转换成键值对,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49329670/