gpt4 book ai didi

java - 如何使用 codehaus.jackson 获取 POJOS 列表的 JSON 数组表示形式

转载 作者:行者123 更新时间:2023-12-02 07:58:00 24 4
gpt4 key购买 nike

我正在寻找一种将 POJO 列表转换为 json 的方法。

我们已经将codehaus jackson与Spring MVC一起使用。我想要实现的不是在带有@ResponseBody操作的ajax调用中,我正在考虑一个将 Pojos 列表转换为 json 数组的 util 方法,但在查看 examples 之后和 ObjectMapper class似乎没有直接的方法来实现它。他们创建了一个 PojoMapper 类来做到这一点。

public static String toJson(Object pojo, boolean prettyPrint)
throws JsonMappingException, JsonGenerationException, IOException {
StringWriter sw = new StringWriter();
JsonGenerator jg = jf.createJsonGenerator(sw);
if (prettyPrint) {
jg.useDefaultPrettyPrinter();
}
m.writeValue(jg, pojo);
return sw.toString();
}

我只是想知道这是推荐的方式。在另一个例子中,他们使用了一个文件,但我无意使用文件而是对象。所以我想知道是否有人可以指出方法。

感谢您阅读本文

最佳答案

您应该能够执行以下操作。

List<POJO> list = ...;
String json = new ObjectMapper().writeValueAsString(list);

如果您是双向父子关系。然后您需要添加注释来告知 Jackson 这种关系。

class Parent {

private Child child;

@JsonManagedReference
Child getChild() {return child;}

void setChild(Child child) {this.child = child;}

}

class Child {

private Parent parent;

@JsonBackReference
Parent getParent() {return parent;}

void setParent(Parent parent) {this.parent = parent;}

}

以上内容告知 jackson 这种关系的循环性质,并且没有试图展开引用的无限循环。这适用于 Jackson 1.6+。我以前没有遇到过这个问题,而且我的机器上没有 Jackson,所以无法正确测试这个问题。

您还应该注意 documentation表示父级不能是集合。

关于java - 如何使用 codehaus.jackson 获取 POJOS 列表的 JSON 数组表示形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9376943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com