![](/img/trans.png)
[英]Spring Boot Failed to Convert JSON to pojo from POST request for fields that are not of type string
[英]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.