簡體   English   中英

Spring Boot-JSON將請求正文同時作為POJO和字符串

[英]Spring boot - json post request body as both POJO and string

在spring boot controller方法中,我可以將json post請求主體映射到POJO

@PostMapping(value = "/abc")
public String handleABC(
        @RequestBody User user
) {
    //code here...
}

我還可以將原始請求正文作為字符串檢索:

@PostMapping(value = "/abc")
public String handleABC(
        @RequestBody String request
) {
    //code here...
}

我的問題是如何將請求主體映射到POJO並檢索原始請求主體作為字符串(用於記錄目的)。

謝謝

通常,默認情況下,SpringBoot將使用Jackson作為序列化框架。

如果沒有任何效果,則可以檢查您的配置,並繼承WebMvcConfigurerAdapter重寫configureMessageConverters序列化方法和特定行為。

像這樣:

I use FastJson as serialization framework, You can set up Jackson's configuration here instead of doing it like I did.

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    /**
     * custom MessageConverter
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter4 converter = new FastJsonHttpMessageConverter4();
        FastJsonConfig config = new FastJsonConfig();
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(converter);
    }
}

這應該工作

@PostMapping(value = "/abc")
public String handleABC(
        @RequestBody String request
) {
    User user = objectMapper.readValue(request,User.class);       
    logger.log(request);
    //code here...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM