gpt4 book ai didi

java - 如何使用 Spring Boot REST 生成自定义 JSON 响应?

转载 作者:行者123 更新时间:2023-12-02 01:32:30 27 4
gpt4 key购买 nike

我正在使用 Spring boot 开发 Restful Web 服务。 CRUD 操作运行良好。但突然出现了新的要求,响应需要采用特定的 JSON 格式。

我收到此回复 -

    "user": {
"id": 123,
"name": "shazow"
}

但是,要求是这样的 -

    {
"Timestamp": "2007-10-27T00:51:57Z"
"status": "ok",
"code": 200,
"messages": [],
"result": {
"user": {
"id": 123,
"name": "shazow"
}
}
}

此外,如果我们检索所有用户,那么它应该是 -

    {
"Timestamp": "2007-10-27T00:51:57Z",
"status": "ok",
"code": 200,
"messages": [],
"users"[
"user": {
"id": 123,
"name": "Shazow"
},

"user": {
"id": 101,
"name": "James"
},

"user": {
"id": 152,
"name": "Mathew"
}
]
}

请帮忙,提前致谢。

最佳答案

您可以在任何类中编写一个方法(如我将其命名为响应处理程序),然后根据需要在其中设置响应。请看下面的代码:

   public class ResponseHandler {

public static ResponseEntity<Object> generateResponse(HttpStatus status, boolean error,String message, Object responseObj) {
Map<String, Object> map = new HashMap<String, Object>();
try {
map.put("timestamp", new Date());
map.put("status", status.value());
map.put("isSuccess", error);
map.put("message", message);
map.put("data", responseObj);

return new ResponseEntity<Object>(map,status);
} catch (Exception e) {
map.clear();
map.put("timestamp", new Date());
map.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
map.put("isSuccess",false);
map.put("message", e.getMessage());
map.put("data", null);
return new ResponseEntity<Object>(map,status);
}
}
}

使用示例:

 @RestController
public class UtilityController {

private static Logger LOGGER = LoggerFactory.getLogger(UtilityController.class);

@RequestMapping("/test")
ResponseEntity<Object> getAllCountry() {
LOGGER.info("Country list fetched");
return ResponseHandler.generateResponse(HttpStatus.OK, false, "Success", null);
}

}

如果您有任何其他疑问,请告诉我。

关于java - 如何使用 Spring Boot REST 生成自定义 JSON 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55822878/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com