【问题标题】:How to add custom attributes in ResponseEntity of Spring Boot Rest api response如何在 Spring Boot Rest api 响应的 ResponseEntity 中添加自定义属性
【发布时间】:2020-05-09 16:57:53
【问题描述】:

由于 spring boot 提供了 ResponseEntity 来表示对 rest api 的 HTTP 响应,包括 headers、body 和 status。

我的 RestController 包含 getTodoById 方法,如下所示-

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

它在 api hit(api/v1/todo/13) 上给出以下 api 响应。

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

应用程序中的所有 api 都需要有一个通用的自定义响应结构,如下所示-

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

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

如何使用 ResponseEntity 获得所需的 JSON 响应结构?

我探索了它,但找不到解决上述问题的解决方案。

任何帮助将不胜感激。 谢谢

【问题讨论】:

标签: java rest spring-boot httpresponse spring-restcontroller


【解决方案1】:

好吧,而不是返回

ResponseEntity.ok(todoItem);

你显然需要返回类似的东西

ResponseEntity.ok(new Response(todoItem));

public class Response {

    private String status = "success";

    private Object data;

    private String error;

    private int statusCode = 200;

    // Constructor, getters and setters omitted
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2019-09-13
    • 2020-10-26
    • 2015-09-04
    • 2016-01-21
    相关资源
    最近更新 更多