我知道MappingMappingJackson2HttpMessageConverter
是默认的,但我得到了
JSON parse error: Unrecognized token 'Stock': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Stock': was expecting ('true', 'false' or 'null')
我认为原因可能是 MappingMappingJackson2HttpMessageConverter
无法将 JSON 数据转换为自定义 POJO,我们必须通过 @Overide
方法 extendMessageConverters()
添加 new HttpMessageConverter
:
/**
* A hook for extending or modifying the list of converters after it has been
* configured. This may be useful for example to allow default converters to
* be registered and then insert a custom converter through this method.
* @param converters the list of configured converters to extend.
* @since 4.1.3
*/
default void extendMessageConverters(List<HttpMessageConverter<?>> converters)
{
}
或者说没有必要?
我尝试了不同的 JSON 样式:{"id":"1"}
,{"Stock":{"id":"1"}}
。但两者都不起作用。
public class myWebApplication extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
WebConfig(DispatcherServlet):
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"WebBeans"})
public class WebConfig implements WebMvcConfigurer
{
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/jsp/",".jsp");
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
我的POJO:
public class Stock
{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
$(document).ready(function() {
$("#button2").click(function() {
$.ajax({
url: "http://localhost:8080/getid2?",
data: {
"Stock": {
"id": "" + $("#id").val()
}
},
type: "POST",
contentType: "application/json;charset=UTF-8",
success: function() {
console.log("successful upload!")
},
error: function() {
console.log("err!")
}
});
})
});
我在 SpringMVC Doc 中找到了这个:
@PostMapping("/accounts")
public void handle(@Valid @RequestBody Account account, BindingResult result)
{
// ...
}
似乎@RequestBody
可以将JSON数据转换为POJO,但它对我不起作用。我在 Chrome 上收到错误 400
请求负载:
Stock%5Bid%5D=4
和
JSON parse error: Unrecognized token 'Stock': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Stock': was expecting ('true', 'false' or 'null')`
原因是什么?
最佳答案
您向后端发送的 json 不正确:
Stock%5Bid%5D=4
正确的请求正文(由 json 转换器解析)应该是:
{
"id": "4"
}
我认为修复可能是:
$.ajax({
...
data: '{"id": "4"}', // Also will work JSON.stringify({id: "4"})
...
});
关于java - 我可以使用默认消息转换器将 JSON 数据转换为 POJO 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56290626/