gpt4 book ai didi

json - 在 Spring 中将 pojo 转换为 JSON 的最佳方法是什么

转载 作者:行者123 更新时间:2023-12-03 09:34:40 27 4
gpt4 key购买 nike

我需要在 Spring 项目中将 POJO 转换为 JSON 字符串。我知道 Spring MVC 通过注释@ResponseBody 提供了一种在 Controller 中返回 json 的便捷方法,我想知道 Spring 如何在内部将 pojo 转换为 JSON?从 Spring MVC maven 依赖关系层次结构中,我找到了 jackson-databind 和 jackson-core 库。在阅读 Jackson 教程时,它说的是不同的库:

<dependencies>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
</dependencies>

转换代码如下:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);

我的问题是:

1:spring restful controller如何将POJO转换为JSON?通过使用 jackson 但不同的依赖库?

2:如果我使用上面的 Jackson 示例将 POJO 转换为 JSON,是否必须将 json 写入文件?是否可以直接获取JSON字符串?

3:Spring项目中POJO转JSON的最佳方式是什么——不使用@ResponseBody,因为我想把POJO转JSON保存到数据库,@ResponseBody是为restful服务的,不适合我的情况。

非常感谢您提前回答。

最佳答案

如果您不想使用 Spring MVC 将对象转换为 JSON 字符串,您可以这样做:

private JsonGenerator jsonGenerator = null;
private ObjectMapper objectMapper = null;
public void init(){
objectMapper = new ObjectMapper();
try{
jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
jsonGenerator.writeObject(bean);
objectMapper.writeValue(System.out, bean);
}catch (IOException e) {
e.printStackTrace();
}
jsonGenerator.flush();
jsonGenerator.close();
}

你必须像这样声明bean
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;

//getters, setters

@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}

关于json - 在 Spring 中将 pojo 转换为 JSON 的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32239629/

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