I'm trying to get a custom response back from a spring rest controller back to the user, containing a list of all registered users and other keys such as sucess, etc. I tried the following approach but the Json array is completly escaped as a string...
@GetMapping(value = "/workers", produces = "application/json;charset=UTF-8")
public ResponseEntity<String> getAllWorkers() throws JSONException {
JSONObject resp = new JSONObject();
ObjectMapper objectMapper = new ObjectMapper();
HttpStatus status;
try {
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
List<Worker> workers = workerservice.getAllworkers();
String json = mapper.writeValueAsString(workers);
resp.put("success", true);
resp.put("info", json);
status = HttpStatus.OK;
} catch (Error | JsonProcessingException e) {
resp.put("success", false);
resp.put("info", e.getMessage());
status = HttpStatus.INTERNAL_SERVER_ERROR;
}
return new ResponseEntity<>(resp.toString(),status);
}
I get something like this
{
"success": true,
"info": "[ {\n \"id\" : 3,\n \"password\" : \"abcdefg\", \n \"tasks\" : [ ], (...) ]"
}
and wanted something like:
{
"success": true,
"info": [
{
"id" : 3,
"password" : "abcdefg",
"tasks" : [ ]
},
(...)
]"
}
Is there any way I can get the json array properly showed after a request?