spring-mvc - 如何在 Spring MVC 的 Rest Controller 中将 Bean 类对象作为 JSON 返回
问题描述
这里我的控制器就像,
@RequestMapping(value = "/restCallRequest", headers =
"Accept=application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Void> callRequest(@RequestBody CallRequestData
requestData, UriComponentsBuilder ucBuilder) {
if (requestData.getIvrName().isEmpty()) {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
System.err.println("IVER Name is "+requestData.getIvrName()+" lsit "+requestData.getContactList().get(0));
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/restCallRequest").buildAndExpand(requestData).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
我的 Bean 类是,
@Entity
public class CallRequestData {
private int id; //Auto incremented
private String ivrName;
private List<String> contactList;
public CallRequestData(int id, String ivrName, List<String> contactList) {
this.id = id;
this.ivrName = ivrName;
this.contactList = contactList;
}
//setters And Getters
我的邮递员在这里发送 JSON
{
"ivr_name":"welcome",
"contactList":[
"9040210495",
"958045830"
]
}
而且我也希望像 Request, { "ivr_name":"welcome", "contactList":[ "9040210495", "958045830" ] }
我该如何解决。提前致谢。
解决方案
在 pom.xml 中添加依赖
<dependency>
<groupId>net.sf.flexjson</groupId>
<artifactId>flexjson</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
在控制器中编写一种方法。
public String toJson(User bean) {
return new JSONSerializer().transform(new DateTransformer("MM/dd/yyyy HH:mm:ss"),java.util.Date.class).serialize(bean);
}
并将您的 bean 对象传递给此方法。
return new ResponseEntity<String>(toJson(bean),headers, HttpStatus.CREATED);
在方法签名中将返回类型更改为字符串public ResponseEntity<String> callRequest
注意:对于 Spring 启动,您可以使用 @RestController 注释,它将自动将对象转换为 json。
推荐阅读
- javascript - valiatorjs 的打字稿导入失败?
- python - 无服务器 AWS Lambda:没有名为“secret_manager”的模块
- java - JVM 类加载器中的可见性原则
- html - 定位元素左右浮动+不可点击的标签
- javascript - 函数未在 nodeJS 类的 setInterval 和 switch/case 中定义
- excel - 将筛选的数据复制到另一个工作簿
- c# - Convert.ToBase64String/Convert.FromBase64String 不返回原始字符串值
- python - Python pandas,按X大小对列进行数据分箱
- powershell - PowerShell 6 在不退出脚本的情况下从 ForEach-Object 循环中中断
- sql-server - 寻找一种特殊的方式加入 SQL 服务器