【问题标题】:Parse request JSON in Spring REST controller called from jQuery ajax在从 jQuery ajax 调用的 Spring REST 控制器中解析请求 JSON
【发布时间】:2020-04-02 16:29:57
【问题描述】:

我正在构建一个 HTML 表单,它在提交时调用 REST api 并以 JSON 格式发送表单值。

像这样:

休息电话:

var url = "http://localhost:8080/backend";
$.ajax({
    url: url,
    type: 'post',
    data: requestJson,
    success: function( data, textStatus, jQxhr ){
        console.log(data);
    },
    error: function( jqXhr, textStatus, errorThrown ){
        console.log( errorThrown );
    }
});

JSON 示例:

{
  "id": "1",
  "domain": "planes",
  "types": [
    "military",
    "commercial"
  ],
  "details": [
    {
      "military": {
        "name": "f18",
        "country": "US"
      }
    },
    {
      "commercial": {
        "name": "a380",
        "country": "Finland"
      }
    }
  ]
}

在后端,我正在运行一个 spring-boot 应用程序,它接受这个 JSON 作为请求并执行一些操作。

class MyRequestDTO {
    @JsonProperty("type")
    private String type;

    @JsonProperty("domain")
    private String domain;

    @JsonProperty("types")
    private String[] types;

    ......
}

控制器中的 REST 调用

@RequestMapping(value = "/save", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Map<String, List<String>> createSot(@Valid MyRequestDTO myRequestDTO) {

    System.out.println(sotDTO.getId());         //THIS WORKS
    System.out.println(sotDTO.getDomain());     //THIS WORKS
    String[] types = sotDTO.getTypes();         //THIS DOES NOT WORK
    for(String e: types) {
        System.out.println("type: " + e);
    }

}

问题是我无法获取类型数组并且它正在抛出空异常。

任何我需要更改的建议。

谢谢

【问题讨论】:

  • 你试过 List 吗?
  • 那应该是一个列表,一个集合。试试劳伦斯的建议。

标签: java jquery json rest spring-boot


【解决方案1】:

private String[] types; 更改为private List&lt;String&gt; types; 会有所帮助。

另外,正如您提到的,您使用 spring-boot 作为后端服务,所以您根本不需要 @JsonProperty 注释。删除它们以减少代码。

【讨论】:

    猜你喜欢
    • 2018-11-24
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多