首页 > 解决方案 > 如何在 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" ] }

我该如何解决。提前致谢。

标签: spring-mvcspring-boot

解决方案


在 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。


推荐阅读