问题描述
我知道如何自定义默认的 ObjectMapper
bean.但是对于一个特定的控制器/端点,我想使用不同的对象映射器.我该怎么做?
I know how to customize the default ObjectMapper
bean. But for one specific Controller/endpoint, I'd like to use a different objectmapper. How can I do this?
我认为我的问题类似于这个 one 但还没有答案.很高兴在那里得到答案并将其标记为重复
I think my question is similar to this one but there are no answers yet. Happy to get an answer there and mark this as duplicate
推荐答案
@xerx593 提供了一个很好的解决方案,链接在问题的评论中,但我采用了不同的方法,因为我返回的是一个通用的 Map<String,Object>
graphql 返回类型,我对更改媒体类型或将对象映射器应用于所有 Map
感到不舒服.我更喜欢他们针对一般情况的解决方案,因为它更优雅
There's a good solution by @xerx593 linked in the question's comments but I took a different approach for mine because I was returning a generic Map<String,Object>
graphql return type and I didn't feel comfortable changing the media-type or applying the object mapper to all Map
's. I prefer their solution for the general case as it's more elegant
我只是将返回对象序列化为字符串并返回.
I simply serialized the return object as a string and returned it.
例如,我变成这样
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public Foo getFoo() {
return new Foo();
}
像这样
private ObjectMapper customMapper = ...;
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public String getFoo() {
return customMapper.writeValueAsString(new Foo());
}
这篇关于是否可以为单个 Spring Rest 端点自定义 ObjectMapper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!