Return Json Object from a Spring-Boot Rest Controller

How to pass JSON Object and return Object from Spring rest controller

To return the status and also the object you can try to do it like this:

@PostMapping(path = "/submitData", consumes = "application/json")
public ResponseEntity<Report> callDataService(@RequestBody Map<String, String> json) {
Gson gson = new GsonBuilder().create();
InputData inputData = gson.fromJson(json.get("inputData"), InputData.class);
Report report = dataService.getReport(inputData);
return ResponseEntity.ok(report);
}

Retrieving a JSON body from DB gives extra special characters - Spring Boot

TL;DR

Just annotated private String responseBody; with @JsonRawValue as follows:

@JsonRawValue
private String responseBody;

Explanation

Because the value of responseBody is a JSON string and @RestController is going to serialize the return object of moreInfo into HttpResponse automatically. That's why you got "extra special characters" in your response body!

Therefore, the simplest way (by using Jackson) is to annotate those fields which you don't want to be serialized again with @JsonRawValue.

For more information, please refer to @JsonRawValue.



Related Topics



Leave a reply



Submit