java - 如何使用 Spring Boot REST 生成自定义 JSON 响应?
问题描述
我正在使用 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);
}
}
如果您有任何其他疑问,请告诉我。
推荐阅读
- python - 在 Python 中对子集运行 for 循环
- google-apps-script - DriveApp 错误:“很抱歉,发生服务器错误。请稍候,然后重试。”
- sql-server - 如何返回每个部门名称和每个部门的员工人数
- javascript - 在 JavaScript 中拆分字符串并移动到换行符
- java - 如何将 GregorianCalendar 转换为 Python / Jython 日期时间?
- javascript - 将相同的数组对象分配给多个变量?
- bash - 有没有办法在 bash 命令中显示函数输出
- jestjs - Jest Babel 错误:测试套件无法运行
- swift - 多次更改 UILabel 属性字符串颜色
- javascript - 避免气泡图中的碰撞