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