首页 > 解决方案 > 我可以使用默认消息转换器将 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')`

是什么原因?

标签: javajqueryjsonspring

解决方案


您正在向后端发送不正确的 json:

Stock%5Bid%5D=4

正确的请求正文(由 json 转换器解析)应该是:

{
  "id": "4"
}

我认为解决方法可能是:

$.ajax({
    ...
    data: '{"id": "4"}', // Also will work JSON.stringify({id: "4"})
    ...
});

推荐阅读