【发布时间】: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