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

标签 java jquery json spring

我知道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/

相关文章:

jquery - 选择前一个元素 - jQuery

javascript - jQuery - 如果 img 在单元格内

javascript - 如何从 JSON 对象填充列表并创建 TreeView - JavaScript

java - Spark App 参数编码

java - 如何在迭代时从 HashMap 中删除一个键?

java - Java 和 PHP 中的 DES 加密

javascript - 除了 input[type=text] 之外的所有内容都禁用选择

php - json 编码和替换 JSON_UNESCAPED_UNICODE

java - 骡子 ESB : Expression Filter with regex() function

java - Ant:如何在多个项目上执行任务