我正在尝试将JSON数据发布到Spring Portlet Controller方法。 Modelattribute对象是嵌套的。这是JSON:
$(document).on({
change: function() {
...
...
formData = {
"name": "Demo",
"id": 724,
"periodId": 2015,
"orgId": 4,
"fieldGroupList": [{
"name": "instructions",
"label": "Instructions",
"fieldList": [{
"name": "INSTRUCTION",
"instructionList": [{
"instructionText": "All enabled fields are required for completion of this screen."
}],
"type": "INSTRUCTION"
}]
}]
};
的Ajax:
$.ajax({
async: "false",
global: "false",
url: validateURL,
type: "POST",
data: formData,
dataType: "json"
}).done(function(json){
console.log(json);
}).fail(function(jqXHR, textStatus, error) {
console.log("responseText: "+jqXHR.responseText);
});
控制器:
@ResourceMapping(value = "validateURL")
public void validate(@ModelAttribute(value = "formData") Measure measure,
BindingResult bindingResult, ResourceRequest request, ResourceResponse response, ModelMap model) throws Exception {
System.out.println("ab:::"+measure.getId());
}
型号:
public class Measure
{
private String name;
private List<MeasureFieldGroup> fieldGroupList = new ArrayList<MeasureFieldGroup>();
...
}
如果将JSON更改为:
,一切正常formData = {
"name": "Demo",
"id": 724,
"periodId": 2015,
"orgId": 4
};
控制器出错:
org.springframework.beans.InvalidPropertyException: Invalid property 'fieldGroupList[0][fieldList][0][instructionList][0][instructionText]' of bean class abc.measures.base.Measure]: Illegal attempt to get property 'fieldGroupList' threw exception; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'fieldGroupList[0][fieldList][0][instructionList][0][instructionText]' of bean class [abc.measures.base.Measure]: Property referenced in indexed property path 'fieldGroupList[0][fieldList][0][instructionList][0][instructionText]' is neither an array nor a List nor a Set nor a Map; returned value was [abc.measures.base.MeasureFieldGroup@72fd67c]
我的问题非常相似 Post Nested Object to Spring MVC controller using JSON和 Spring Portlet Jquery Ajax post to Controller
但由于Spring Portlet无法使用ResponseBody和RequestBody。任何帮助都会受到很多赞赏。
由于
答案 0 :(得分:1)
当我尝试将JSON数组绑定到Spring portlet MVC中的模型时,我遇到了这个问题。我不知道问题是春天还是我构建JSON数组的方式。
我找到的解决方案是:
使用JSON.stringify将对象(在本例中为数组)转换为具有JSON格式的字符串。例如:
formData = {
"name": "Demo",
"id": 724,
"periodId": 2015,
"orgId": 4,
"fieldGroupString": JSON.stringify(fieldGroupList)
};
其中fieldGroupList是javascript中的数组。
然后,您可以使用jackson库的ObjectMapper类将JSON字符串转换为模型中的对象列表。
public void setFieldGroupString(String fieldGroupString) {
if(fieldGroupString != null){
ObjectMapper mapper = new ObjectMapper();
fieldGroupList = new ArrayList<MeasureFieldGroup>();
try {
fieldGroupList = mapper.readValue(fieldGroupString,
new TypeReference<List<MeasureFieldGroup>>() {
});
} catch (Exception e) {
logger.debug("Error in mapper");
}
}
}