AJAX - 后台解析前台传的JSON数组
发布时间:2020-12-16 03:32:34 所属栏目:百科 来源:网络整理
导读:前面讲了前台传JSON到后台,只是单独一个json,这里说明一下前台传JSON数组到后台如何接收并转换 注意,前台ajax : 若为自定义contentType,通过前篇讲述的第二种接收方法,获取jsonStr,之后过程类似。 contentType : "application/x-www-form-urlencoded"
前面讲了前台传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: 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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |