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

Transform map into key value pairs with Genson

我正在使用 Genson 将 Java class 序列化为 JSON。 class 成员之一是 Map,我需要将其直接序列化为 name/value 对。例如:

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.