使用Genson将地图转换为键值对

时间:2018-03-16 21:18:14

标签: java json serialization genson

我使用Genson将Java类序列化为JSON。其中一个类成员是Map,我需要将其直接序列化为名称/值对。例如:

{
    "name":"Myname",
    "Book": "My book title",
    "Fruit": "Orange"
}

我需要序列化:

{
    "name":"Myname",
    "mp":{
        "Book": "My book title",
        "Fruit": "Orange"
    }
}

我尝试应用Genson,我接近其默认操作,输出为:

install

保证mp中的键不会与Demo的任何成员发生冲突。

如何使用Genson实现此用例?

1 个答案:

答案 0 :(得分:2)

可以通过实现自定义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