如何使用Spring Boot REST生成定制的JSON响应?

时间:2019-04-24 05:21:37

标签: java json rest spring-boot

我正在使用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"
               }
          ]     
     }

请帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

您可以在任何类中编写一种类似于我命名为Response handler的方法,然后根据需要在其中设置响应。请查看下面的代码:

   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);
    }

}

如果还有其他疑问,请告诉我。