简体   繁体   中英

How to generate customized JSON response with Spring Boot REST?

I am developing Restful web services with Spring boot. And the CRUD operations are working fine with it. But suddenly new requirement has come that the response needs to be in specific JSON format.

I am getting this response -

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

But, the requirement is something like this -

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

Also, if we retrieve all users then it should be -

    {
       "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"
               }
          ]     
     }

Please help, thanks in advance.

You can write a method like I name it response handler in any class and then set your response in it as you like. Please see the code below:

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

Example to use :

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

}

If you have any other queries, please do let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM