java - 我可以使用默认消息转换器将 JSON 数据转换为 POJO 吗?
问题描述
我知道MappingMappingJackson2HttpMessageConverter
是默认的,但我得到了
JSON解析错误:无法识别的令牌'Stock':期待('true','false'或'null');嵌套异常是 com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Stock': was expected ('true', 'false' or 'null')
我认为可能的原因是MappingMappingJackson2HttpMessageConverter
无法将 JSON 数据转换为自定义 POJO,我们必须new HttpMessageConverter
通过@Overide
方法添加extendMessageConverters()
:
/**
* 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)
{
}
还是不需要?</p>
我尝试了不同的 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 expected ('true', 'false' or 'null')`
是什么原因?
解决方案
您正在向后端发送不正确的 json:
Stock%5Bid%5D=4
正确的请求正文(由 json 转换器解析)应该是:
{
"id": "4"
}
我认为解决方法可能是:
$.ajax({
...
data: '{"id": "4"}', // Also will work JSON.stringify({id: "4"})
...
});
推荐阅读
- python - 在 wxPython 中填充快捷方式编辑器
- html - 正则表达式:尽可能匹配直到下一场比赛
- python - 如何在python中使用硒选择下拉列表的值
- javascript - 创建导航器时,未定义不是对象(评估 this.props.navigation.navigate)
- regex - 带有黑名单的骆驼案例的正则表达式
- java - 在 CN (Java) 中删除 0x0A 的 LDAP 记录
- python - 如何在 Python 中格式化语句和循环?
- python - 如何使用 Python 更新计划事件中的变量?
- c++ - C++ 字符串操作
- r - R BootStrap 数据帧