问题描述
- java后台如何解析这样的json串?jsonObject和JsonArray不好用,有别的方式吗
-
[{"_sortNum":0,"_photoId":"2402 ","_updateTime":"2015-12-11 14:55:32","_updateUserName":" ","_ynRelease":1},
{"_sortNum":1,"_photoId":" 2222 ","_updateTime":" 22:22:22 ","_updateUserName":" 张2222 ","_ynRelease":1},
{"_sortNum":2,"_photoId":" 3333 ","_updateTime":" 33:33:33 ","_updateUserName":" 张3333 ","_ynRelease":1},
{"_sortNum":3,"_photoId":" 4444 ","_updateTime":" 44:44:44 ","_updateUserName":" 张4444 ","_ynRelease":1},
{"_sortNum":4,"_photoId":" 5555 ","_updateTime":" 55:55:55 ","_updateUserName":" 张5555 ","_ynRelease":1},{"_sortNum":5,"_photoId":" 6666 ","_updateTime":" 66:66:66 ","_updateUserName":" 张6666 ","_ynRelease":1},{"_sortNum":6,"_photoId":" 7777 ","_updateTime":" 77:77:77 ","_updateUserName":" 张7777 ","_ynRelease":1},{"_sortNum":7,"_photoId":" 8888 ","_updateTime":" 88:88:88 ","_updateUserName":" 张8888 ","_ynRelease":1},{"_sortNum":8,"_photoId":" 9999 ","_updateTime":" 99:99:99 ","_updateUserName":" 张9999 ","_ynRelease":1}]
解决方案
这个格式就是Array的格式,就是需要用JSONArray解析的,检查下是不是你的代码有什么不妥的地方呢?
解决方案二:
创建对象的方法可以试试;或者用map也可以。
public static void ParseJson(String jsonString) {
// 以employee为例解析,map类似
JSONObject jb = JSONObject.fromObject(jsonString);
JSONArray ja = jb.getJSONArray("user");
List<Offers> userList = new ArrayList<Offers>();
// 循环添加User对象(可能有多个)
for (int i = 0; i < ja.size(); i++) {
Offers user = new Offers();
user.setName(ja.getJSONObject(i).getString("name"));
user.setSex(ja.getJSONObject(i).getString("sex"));
user.setAge(ja.getJSONObject(i).getInt("age"));
userList.add(user);
}
System.out.println("n将Json数据转换为User对象:");
for (int i = 0; i < userList.size(); i++) {
Offers user = userList.get(i);
System.out.println("age: " + user.getAge() + "nname: "
+ user.getName() + "nsex: " + user.getSex());
}
// map:
JSONArray JMap = jb.getJSONArray("map");
List<Map<String, Object>> mapList = new ArrayList<Map<String,Object>>();
Map<String, Object> maps = null;
for (int i = 0; i < JMap.size(); i++) {
maps = new HashMap<String, Object>();
maps.put("name", JMap.getJSONObject(i).get("name"));
maps.put("sex", JMap.getJSONObject(i).get("sex"));
maps.put("age", JMap.getJSONObject(i).get("age"));
mapList.add(maps);
}
System.out.println("n将Json数据转换为Map类型");
for (int i = 0; i < mapList.size(); i++) {
Map<String, Object> map = mapList.get(i);
System.out.println("age: " + map.get("age") + "nname: "
+ map.get("name") + "nsex: " + map.get("sex"));
}
}
解决方案三:
用Gson试试,,,再不行的话,,直接用实体类封装就行了
解决方案四:
先转化成 jsonArray ,再遍历 jsonArray, 通过jsonObject获取信息
时间: 2024-11-02 07:17:58