【发布时间】:2019-10-10 22:30:00
【问题描述】:
我知道MappingMappingJackson2HttpMessageConverter 是默认值,但我知道了
JSON 解析错误:无法识别的令牌 'Stock':期待('true'、'false' 或 'null');嵌套异常是 com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Stock': was expected ('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 解析错误:无法识别的令牌 'Stock':期待('true'、'false' 或 'null');嵌套异常是 com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Stock': was expecting ('true', 'false' or 'null')`
是什么原因?
【问题讨论】:
-
你能添加
Account类吗? -
能否附上从前端收到的 json?该错误告诉您您正在尝试将 Stock 值设置为 Bollean 变量
-
@Arnaud 来自 Spring Doc,
Account未列出。 -
嗨@alexey28,
Stock%5Bid%5D=4