前面讲了前台传JSON到后台,只是单独一个json,这里说明一下前台传JSON数组到后台如何接收并转换
注意,前台ajax:
若为自定义contentType,通过前篇讲述的第二种接收方法,获取jsonStr,之后过程类似。
contentType:"application/x-www-form-urlencoded",//默认值
@H_301_14@data : {mydata:jsonArrayFinal},
//@H_301_14@data为键值对形式
【方法一】
将得到的json数组字符串转换为 list【使用jackson】:
String jsonStr = getRequest().getParameter("mydata");
System.@H_301_14@out.println(jsonStr);
//json-jackson
ObjectMapper objectMapper = @H_301_14@new ObjectMapper();
List readValue = @H_301_14@null;
@H_301_14@try {
readValue = objectMapper.readValue(jsonStr,List.class);
System.@H_301_14@out.println("转换后的list :"+readValue);
@H_301_14@for (Object @H_301_14@object : readValue) {
String objectToJson = objectMapper.writeValueAsString(@H_301_14@object);
System.@H_301_14@out.println("将list[i]转换为json:"+objectToJson);
Person person = objectMapper.readValue(objectToJson,Person.class);
System.@H_301_14@out.println("每一个list[i]封装后的model:"+person);
}
} @H_301_14@catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} @H_301_14@catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} @H_301_14@catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@H_301_14@return @H_301_14@null;
【方法二】
利用JSONArray和JSONObject:
【json - json_lib】
String jsonStr = getRequest().getParameter("mydata");
System.@H_301_14@out.println(jsonStr);
JSONArray jsonArray = @H_301_14@new JSONArray();
JSONObject jsonObject = @H_301_14@new JSONObject();
JSONArray jsonToArray = jsonArray.fromObject(jsonStr);
ObjectMapper objectMapper = @H_301_14@new ObjectMapper();
@H_301_14@for(@H_301_14@int i=0;i<jsonToArray.size();i++){
jsonObject = jsonToArray.getJSONObject(i);
Person person = (Person) jsonObject.toBean(jsonObject,Person.@H_301_14@class);
System.@H_301_14@out.println(person);
}
@H_301_14@try {
@H_301_14@out(jsonStr);
} @H_301_14@catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@H_301_14@return null;