我可以使用默认消息转换器将JSON数据转换为POJO吗?

时间:2019-05-24 10:17:32

标签: java jquery json spring

我知道MappingMappingJackson2HttpMessageConverter是默认设置,但我知道了

  

JSON解析错误:无法识别的令牌“ Stock”:预期中(“ true”,“ false”或“ null”);嵌套的异常是com.fasterxml.jackson.core.JsonParseException:无法识别的令牌“ Stock”:正在等待(“ true”,“ false”或“ 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) 

{
}

还是没有必要?

我尝试了不同的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:无法识别的令牌“ Stock”:正在期待(“ true”,“ false”或“ null”)`

原因是什么?

1 个答案:

答案 0 :(得分:0)

您向后端发送了错误的json:

Stock%5Bid%5D=4

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

{
  "id": "4"
}

我认为解决方法可能是:

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