我正在构建一个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;
......
}
Controller中的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
注释。删除它们以减少代码。