使用不同的jackson ObjectMapper进行单独的RequestMapping

时间:2017-07-17 23:09:33

标签: java spring spring-boot jackson objectmapper

我有一个使用自定义MIME类型的@RequestMapping。该请求使用ObjectMapper中定义的@Configuration bean来启用JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER

此功能通常允许使用无效的json(将反斜杠视为非特殊字符),这是此特定@RequestMapping允许直接解析谷歌编码折线的要求。但是,这意味着此ObjectMapper现在用于@RequestMapping ALL ,而实际上只需要一个。{/ p>

有没有办法区分每个@Controller@RequestMapping使用的ObjectMapper?

对象映射器Bean

@Bean
public ObjectMapper objectMapper() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.featuresToEnable(
      JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER);

    return builder.build();
}

请求映射接口方法

@ApiOperation(value = "Returns the toll cost breakdown for a journey", notes = "", response = TotalCost.class, tags={ "pricing", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "successful operation", response = TotalCost.class) })
@RequestMapping(value = "/pricing/journeyCost",
    produces = { "application/json" }, 
    consumes = { "application/vnd.toll-pricing+json" },
    method = RequestMethod.POST)
ResponseEntity<TotalCost> getTollBreakdownFromEncodedPoly(@ApiParam(value = "Request object representing the journey" ,required=true ) @RequestBody Journey body);

2 个答案:

答案 0 :(得分:1)

如果您使用的是自定义MIME类型,那么您可以注册一个自定义HttpMessageConverter,其中使用特殊ObjectMapper作为您的MIME类型,并从{{1}返回false对于常规MIME类型。您可以像这样注册自定义canRead/canWrite

HttpMessageConverter

将其视为与内容协商相关,与URL映射无关; URL映射(@EnableWebMvc @Configuration @ComponentScan public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters) { messageConverters.add(myCustomMessageConverter()); super.configureMessageConverters(converters); } } )用于查找处理程序,而不是用于选择要使用的marshaller / unmarshaller。

答案 1 :(得分:1)

我在另一个用户链接到我的另一个stackoverflow问题中找到了答案 - https://stackoverflow.com/a/45157169/2073800

我只需将以下@Bean添加到@Configuration

@Bean
public HttpMessageConverters customConverters() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.featuresToEnable(
      JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER);

    final AbstractJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(builder.build());
    converter.setSupportedMediaTypes(Collections.singletonList(MediaType.valueOf("application/vnd.toll-pricing+json")));

    return new HttpMessageConverters(converter);
}