簡體   English   中英

如何使用Spring Boot REST生成自定義JSON響應?

[英]How to generate customized JSON response with Spring Boot REST?

我正在使用Spring啟動開發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);
    }

}

如果您有任何其他疑問,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM