繁体   English   中英

在从 jQuery ajax 调用的 Spring REST 控制器中解析请求 JSON

[英]Parse request JSON in Spring REST controller called from jQuery ajax

我正在构建一个 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);
    }

}

问题是我无法获取类型数组 & 它抛出空异常。

任何建议我需要改变什么。

谢谢

更改private String[] types; private List<String> types; 有助于。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM