【发布时间】:2013-02-05 00:11:00
【问题描述】:
基本上,我有一些 Java 对象,我想尽可能少地把它们序列化为 JSON。现在我正在使用 Tomcat、Jersey 和 Genson。
我发现这样的事情对 Genson 不起作用(当然,这是一个玩具示例):
public class Main {
public static void main(String[] args) {
MyClass mc = new MyClass();
mc.mapOfSets = new HashMap<>();
Set<String> set0 = new HashSet<>();
set0.add("0");
Set<String> set1 = new HashSet<>();
set1.add("1");
set1.add("11");
Set<String> set2 = new HashSet<>();
set2.add("2");
set2.add("22");
set2.add("222");
mc.mapOfSets.put("set0", set0);
mc.mapOfSets.put("set1", set1);
mc.mapOfSets.put("set2", set2);
try {
String json1 = new Genson().serialize(mc.mapOfSets);
System.out.println(json1);
String json = new Genson().serialize(mc);
System.out.println(json);
} catch (TransformationException | IOException e) {
e.printStackTrace();
}
}
}
class MyClass {
public Map<String, Set<String>> mapOfSets;
}
上面的输出是这样的:
{"set1":["1","11"],"set0":["0"],"set2":["2","222","22"]}
{"mapOfSets":{"empty":false}}
Genson 的优点在于我只是将它放到了我的 WebContent 文件夹中,然后使用它来代替 Jersey 捆绑的任何东西 - 不需要额外的配置。如果有一种非常直接的方法可以让像上面这样的对象序列化为 JSON,而不必为每个模式编写某种转换器,我很乐意将它与 Jersey 而不是 Genson 一起使用,但 Genson 并没有因此让我失望缺点很多。
那么 - 我如何按摩 Genson 以正确序列化 - 或者什么是可以轻松处理此类事情的库?
谢谢!
【问题讨论】:
-
发布完成,看我的编辑