2017-07-17 226 views
1

我有一個使用自定義MIME類型的@RequestMapping。該請求使用在@Configuration中定義的ObjectMapper Bean來啓用JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER使用不同的傑克遜ObjectMappers進行單獨的RequestMapping

此功能允許消耗通常無效的json(將反斜槓當作非特殊字符),這是此特定@RequestMapping的要求,以允許直接解析谷歌編碼多段線。然而這意味着這個ObjectMapper現在被用於我的@RequestMapping全部,當它真的只是一個需求的時候。

有沒有辦法區分每個@Controller@RequestMapping使用的ObjectMapper?

對象映射豆

@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); 
+0

你想的只是自定義處理旅程界面? – 2017-07-18 00:13:24

+0

@lexknuther本質上是的。 – Jags

+0

另外,你使用的是什麼版本的傑克遜? – 2017-07-18 00:55:29

回答

0

我發現另一個用戶連接到我的另一個計算器問題的答案 - 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); 
} 
1

如果您已經自定義MIME類型,那麼你就可以註冊一個自定義HttpMessageConverter使用特殊ObjectMapper對於您的MIME類型,並從canRead/canWrite返回false以獲得常規MIME類型。註冊您的自定義HttpMessageConverter像這樣:作爲有關內容協商

@EnableWebMvc 
@Configuration 
@ComponentScan 
public class WebConfig extends WebMvcConfigurerAdapter { 

    @Override 
    public void configureMessageConverters(
     List<HttpMessageConverter<?>> converters) { 

     messageConverters.add(myCustomMessageConverter()); 

     super.configureMessageConverters(converters); 
    } 
} 

想起來了,並沒有涉及到URL映射; URL映射(@RequestMapping)用於查找處理程序,而不是用於選擇要使用的編組/解組器。

+0

瞭解內容談判和對我的問題的評論指出我在正確的方向。我不懷疑上述解決方案會起作用,但我發現稍微容易一些。 – Jags

+0

@Jags我看了一下Szymon Stepniak在另一個線程中的內容,除了註冊轉換器的部分之外,它與我所說的完全相似。當你說你不懷疑上述會發揮作用時,我懷疑你並不真正瞭解發生了什麼。 –

+0

我並不不同意你的答案是相似的,但是他的答案更易於遵循並更好地解釋。我也同意我可能完全不瞭解錯綜複雜的情況,但也許這也反映了你答案的質量?我應用了你的答案,根據我的理解,我創建了一個「HttpMessageConverter」的自定義實現,並覆蓋了只接受一個「MediaType」的方法。 Szymons的回答更加簡潔直接。 – Jags