【问题标题】:How to return Bean class Object as JSON in Rest Controller in Spring MVC如何在 Spring MVC 的 Rest Controller 中将 Bean 类对象作为 JSON 返回
【发布时间】:2018-12-08 06:36:08
【问题描述】:

我的控制器是这样的,

 @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

这里我的 POSTMAN 发送 JSON

{
    "ivr_name":"welcome",
    "contactList":[
           "9040210495",
           "958045830"
    ]
}

我也希望像请求一样响应, { "ivr_name":"欢迎", “联系人列表”:[ "9040210495", “958045830” ] }

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

【问题讨论】:

    标签: spring-mvc spring-boot


    【解决方案1】:

    在 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&lt;String&gt; callRequest中将返回类型更改为字符串

    注意:对于 Spring 启动,您可以使用 @RestController 注释,它会自动将对象转换为 json。

    【讨论】:

    • @RestController 将为整个类设置转换,如果您的某些方法不想要该功能,您可以在需要该功能的方法上使用@ResponseBody
    • 正是..这就是我在这里给出两个选项的原因..谢谢。
    • 你能在这里改变我的所有控制器吗?在这里我收到返回错误。感谢您的评论。我是春天的新人。 @外星人
    • 请给我一些时间。
    • 感谢@Alien 给了我一个样本。这是一个非常有帮助的。再次感谢。
    【解决方案2】:

    添加 Jackson 依赖项

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.4</version>
      <scope>provided</scope>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.4</version>
      <scope>provided</scope>
    </dependency> 
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.4</version>
      <scope>provided</scope>
    </dependency>
    

    并添加

    @RequestMapping(value="/endpoint",produces="application/json",method=RequestMethod.POST)
    

    produces="application/json" 到请求映射。 \

    现在无论如何,在@ResponseBody 之后定义的bean 将作为json 对象返回给客户端。无需在外部将其解析为 json。

    【讨论】:

      【解决方案3】:

      我不明白你为什么要做出所有这些选择。 就是这么简单。

      如果你的控制器被@RestController注解,你只需要像这样返回对象:

      @RequestMapping..................................)
       public ResponseEntity<CallRequestData> callRequest(@RequestBody CallRequestData 
       requestData, UriComponentsBuilder ucBuilder) {
      

      .......这里的代码......

        return new ResponseEntity<>(requestData, HttpStatus.CREATED); 
      

      }

      在响应实体上设置返回类型,然后像这样返回一个新的 ResponseEntity 实例。

      我建议你避免多次返回,将一个变量分配给 ResponseEntity 并在方法结束时只返回一次

      【讨论】:

      • 但它给出了错误,HTTP Status 404 – Not Found Status Report Message /restCallRequest Description.The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. In POSTMAN
      • 你是如何设置@RequestMapping 在我的例子中还有一个 CallReqestData 作为输入.. 告诉我你的方法
      • 很好,但是又出现了一个错误HTTP Status 403 – Forbidden Type Status Report. Message: Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.Description. The server understood the request but refuses to authorize it.,感谢回复。
      • @RequestMapping(value = "/restCallRequest", headers = "Accept=application/json", method = RequestMethod.POST) public ResponseEntity&lt;CallRequestData&gt; callRequest(@RequestBody CallRequestData requestData, UriComponentsBuilder ucBuilder) { if (requestData.getIvrName().isEmpty()) { return new ResponseEntity&lt;CallRequestData&gt;(HttpStatus.CONFLICT); } System.err.println("IVER Name is "+requestData.getIvrName()+" lsit "+requestData.getContactList().get(0)); return new ResponseEntity&lt;&gt;(requestData, HttpStatus.CREATED); }
      • 在安全配置中添加 http.csrf().disable();或者您也必须以这种方式传递令牌:
      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 2015-09-02
      • 2015-07-24
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      相关资源
      最近更新 更多