Setting gson as the preferred mapper via the spring.mvc.converters.preferred-json-mapper
config property has the effect of the GsonHttpMessageConverter
being inserted first in HttpMessageConverters
, which has the consequence of giving it the highest priority; when Jackson is used, the other default converters such as ByteArrayHttpMessageConverter
and StringHttpMessageConverter
are still higher priority and thus have a chance to run.
Example:
@Controller
public class ExampleController {
@RequestMapping(value = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
public String test() {
return "{\"data\": \"example\"}";
}
}
The above code, will work when Jackson is the default mapper, as StringHttpMessageConverter
will handle the response and pass it through unescaped / unquoted. When gson is set as the preferred mapper, GsonHttpMessageConverter
ends up double encoding the JSON, and you get a mangled response. The same problem arises if you have a method which attempts to return a StreamingResponseBody
, etc.
In my opinion, simply switching JSON mappers should not have these other unintended side effects, and the behavior should not diverge this severely; ideally the Gson message converter would be inserted in the position that the Jackson converter currently sits in terms of priority, after StringHttpMessageConverter
et al.
Comment From: wilkinsona
Thanks for the report, @kilink. I think you could work around this by defining your own HttpMessageConverters
bean that overrides postProcessConverters
(and possibly postProcessPartConverters
as well) to return a list that's been sorted to meet your needs.
Comment From: kilink
Yes, providing a custom HttpMessageConverters
works, as does providing a WebMvcConfigurer
bean that does this sorting in extendMessageConverters
.
My point though is that it feels inconsistent to need to customize it when using the spring.mvc.converters.preferred-json-mapper
property, if I have to write code anyway then what is the point of the configuration? And maybe the ordering of converters is not API / explicitly guaranteed but I suspect lots of applications rely on the default ordring.
Comment From: wilkinsona
Sorry for the confusion. I understood your point and agree with it, hence I've labelled this issue as a bug and assigned it to the 2.4.x milestone. I was just suggesting something that would hopefully get you going again while we fix the problem.