Search code examples
jsonspringspring-boothttpresttemplate

How to get pretty formatted ResponseEntity for Custom Response Model?


When I am returning String for ResponseEntity it shows pretty formatted json in Postman but when I am returning CustomModel for ResponseEntity, it shows non formatted json.

Code 1:

@PostMapping("/json1")
ResponseEntity<String> getData1() {

    String result = "{\"name\":\"Alex\"}";
    return ResponseEntity.ok().body(result);
}

Postman output 1:

{
  "name": "Alex"
}

Code 2:

class RestResp {

    public ResponseEntity<?> data = null;
}

@PostMapping("/json2")
ResponseEntity<RestResp> getData2() {

    String result = "{\"name\":\"Alex\"}";
    RestResp response = new RestResp();
    response.data = ResponseEntity.ok().body(result);
    return ResponseEntity.ok().body(response);
}

Postman output 2:

{
    "data": {
        "headers": {},
        "body": "{\"name\":\"Alex\"}",
        "statusCode": "OK",
        "statusCodeValue": 200
    }
}

Why am I getting "{\"name\":\"Alex\"}" non formatted? How can I get the properly formatted json in Postman?


Solution

  • You can do it in many ways.

    With dedicated object:

    class Person {
    
        private String name;
    
        public Person(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    and

        RestResp response = new RestResp();
        response.data = ResponseEntity.ok().body(new Person("Alex"));
        return ResponseEntity.ok().body(response);
    

    Map it to json:

        String result = "{\"name\":\"Alex\"}";
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(result);
    
        RestResp response = new RestResp();
        response.data = ResponseEntity.ok().body(node);
        return ResponseEntity.ok().body(response);
    

    Or just use a map:

        Map<String,Object> map = new HashMap<>();
        map.put("name", "Alex");
    
        RestResp response = new RestResp();
        response.data = ResponseEntity.ok().body(map);
        return ResponseEntity.ok().body(response);