0

基本上,我有一些 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 以正确序列化 - 或者什么是无痛处理这类事情的库?

谢谢!

4

2 回答 2

2

我是 Gensons 的作者。我刚刚检查过,这是一个错误,除此特殊情况外,泛型在 Genson 中工作正常……如果你能等到明天,我将在今晚推出一个新版本,其中包含修复和一些小的新功能。完成后我会更新我的答案。

编辑错误更正并将发布 0.94 推送到公共 maven 存储库,它应该在最多几个小时内可用。以下是此版本中的一些更改。请尝试并确认它是否能解决您的问题。谢谢 :)

于 2013-02-05T08:53:35.910 回答
0

我正在使用 Guice 来处理我的依赖注入需求,这就是为什么我很难让 Jackson 与我的 Jersey 项目集成。由于 Genson 没有做我想做的事,我决定再次尝试 Jackson。我尝试改变几件事,直到它起作用,在 SO 和 Google 上尝试不同的建议。

现在下面给出了我的沙盒项目中预期的输出:

ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
String jsonData = mapper.writeValueAsString(mc);
System.out.println(jsonData);

{"mapOfSets":{"set1":["1","11"],"set0":["0"],"set2":["2","222","22"]}}
于 2013-02-05T01:41:31.480 回答