
Spring REST controllers and returning JSON strings
So I noticed an issue with our Spring Boot REST API returning strings unquoted and with the wrong
Content-Type
, which will cause issues with clients looking for a JSON response. The underlining
issue is that when Spring sees a String
response, it calls StringHttpMessageConverter
for the
response and not MappingJackson2HttpMessageConverter
.
The fix was to turn any String
controller method response from this:
@PostMapping("/myresource/create")
public String createMyResource(@RequestBody MyResourceRequest request) {
return this.myResourceService.create(request);
}
into this:
@PostMapping("/myresource/create")
public @ResponseBody char[] createMyResource(@RequestBody MyResourceRequest request) {
return this.myResourceService.create(request).toCharArray();
}
This is very ugly, and I would have rather found another way, but it works.
EDIT - 2020-06-30: Another solution:
@PostMapping("/myresource/create")
public TextNode createMyResource(@RequestBody MyResourceRequest request) {
// as long as create() returns a string
return new TextNode(this.myResourceService.create(request))
}