简体   繁体   English

如何在 Spring Boot Rest api 响应的 ResponseEntity 中添加自定义属性

[英]How to add custom attributes in ResponseEntity of Spring Boot Rest api response

As spring boot provides the ResponseEntity to represent a HTTP response for rest apis, including headers, body, and status.由于 Spring Boot 提供了 ResponseEntity 来表示 rest apis 的 HTTP 响应,包括 headers、body 和 status。

My RestController contains getTodoById method like below-我的 RestController 包含 getTodoById 方法,如下所示-

@GetMapping("/todo/{id}")
 public Todo getTodoById(@PathVariable String id) {
        int todoId = Integer.parseInt(id);
        Todo todoItem = todoRepository.findById(todoId);
         ResponseEntity.ok(todoItem);
    }

It gives the following api response on api hit(api/v1/todo/13).它在 api hit(api/v1/todo/13) 上给出了以下 api 响应。

{
    "id": 13,
    "title": "title13",
    "status": "not started"
}

There is need to have a common customised response structure for all apis in the application as below-应用程序中的所有 api 需要有一个通用的自定义响应结构,如下所示 -

{
  "status": "success",
  "data": {
    "id": 13,
    "title": "title13",
    "status": "not started"
  },
  "error": null,
  "statusCode": 200
}

{
  "status": "failure",
  "data": {},
  "error": "bad request",
  "statusCode": 400
}

How do i get the required JSON response structure using ResponseEntity?如何使用 ResponseEntity 获取所需的 JSON 响应结构?

I explored it but could not find the solution which solve the above problem.我探索了它,但找不到解决上述问题的解决方案。

Any help would be appreciated.任何帮助,将不胜感激。 Thanks谢谢

Well, instead of returning好吧,而不是返回

ResponseEntity.ok(todoItem);

you obviously need to return something like你显然需要返回类似的东西

ResponseEntity.ok(new Response(todoItem));

with

public class Response {

    private String status = "success";

    private Object data;

    private String error;

    private int statusCode = 200;

    // Constructor, getters and setters omitted
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM