前端向后端传对象数组--方式一

1.定义一个键值对对象
function ObjData(key,value){
this.key=key;
this.value=value;
}

2.定义一个对象数据
var existUserArray=[]; //定义一个对象数据。
遍历map,构造对象,写入对象数组中。
existUserMap.forEach(function (item, key, mapObj) {
var s=new ObjData(key,item); //创建键值对象
existUserArray.push(s); //把对象放入对象数组中
});

3.把数组转换成json字符串。
var existUserStr = JSON.stringify(existUserArray);


4.使用post提交数据
var data = {
"existUserStr": existUserStr
};
$.post(
"saveUsers",
data,
function (ret) {
console.info(ret);
},
"Json" //important
); //post

5.java后端处理
@RequestMapping(value = "/saveUsers", method = RequestMethod.POST)
@ResponseBody
public Map saveUsers(Model model, String existUserStr, String selectedUserStr) {
Map result = Maps.newHashMap();
String msg = "成功!";
String success = "true";
try {
List existUserList = JsonMapper.fromJson(existUserStr, List.class, ObjData.class);
List selectedUserList = JsonMapper.fromJson(selectedUserStr, List.class, ObjData.class);
System.out.println();
} catch (Exception e) {
log.warn("", e);
msg = "失败 ";
success = "false";
}

result.put("success", success);
result.put("message", msg);
return result;
}

6.附上jsonmapper的fromjson方法.
// @SuppressWarnings("unchecked")
public static T fromJson(String json, Class collectionClass, Class... elementClasses) {
if (json==null||json.trim().isEmpty()) {
return null;
}

try {
JavaType type = JsonMapper.getInstance().getTypeFactory().constructParametricType(collectionClass, elementClasses);
return (T) JsonMapper.getInstance().readValue(json, type);
} catch (IOException e) {
logger.warn("parse json string error:" + json, e);
e.printStackTrace();
return null;
}
}

你可能感兴趣的:(js,js,数组,前后台交互)