java 解析Json数据
一、普通json格式
如:{“name”:“乔治”,“id”:1}
private void getObject(String json){ JSONObject jsonObject = JSON.parseObject(json); String id = jsonObject.getString("id"); String s = jsonObject.getString("name"); System.out.println(id); System.out.println(s); }
二、json中包含对象
如:{“user”:{“id”:2,“name”:“王”}}
private void getObject2(String json){ JSONObject jsonObject = JSON.parseObject(json); JSONObject user = jsonObject.getJSONObject("user"); Integer id = user.getInteger("id"); String name = user.getString("name"); System.out.println(id); System.out.println(name);}
三、json中包含list集合
如:{“list”:[{“id”:3,“name”:“忘3”},{“id”:4,“name”:“忘4”},{“id”:5,“name”:“忘5”},{“id”:6,“name”:“忘6”},{“id”:7,“name”:“忘7”},{“id”:8,“name”:“忘8”},{“id”:9,“name”:“忘9”},{“id”:10,“name”:“忘10”}]}
private void getArray(String json){ List list = new ArrayList(); JSONObject jsonObject = JSON.parseObject(json); JSONArray userList = jsonObject.getJSONArray("list"); for (int i = 0; i < userList.size();i++){ User2 user2 = new User2(); JSONObject jsonObject1 = userList.getJSONObject(i); System.out.println(jsonObject1.toString()); user2.setId(jsonObject1.getInteger("id")); user2.setName(jsonObject1.getString("name")); list.add(user2); } System.out.println(JSON.toJSON(list)); }
四、json中包含map集合
如 :{“map”:{“钱”:“14”,“赵”:“12”,“王”:“13”}}
private void getMap(String json){ JSONObject jsonObject = JSON.parseObject(json); JSONObject map = jsonObject.getJSONObject("map"); //获取到所有的key Set strings = map.keySet(); //h获取迭代器 Iterator iterator = strings.iterator(); while(iterator.hasNext()){ String next = iterator.next(); String string = map.getString(next); System.out.println(next+":"+string); } }
五、json中包含list
如:{“listMap”:[{“钱”:“14”,“赵”:“12”,“王”:“13”},{“钱2”:“14”,“王2”:“13”,“赵2”:“12”}]}
private void getListMap(String json){ JSONObject jsonObject = JSON.parseObject(json); JSONArray listMap = jsonObject.getJSONArray("listMap"); for (int i = 0;i<listMap.size();i++){ JSONObject jsonObject1 = listMap.getJSONObject(i); Set strings = jsonObject1.keySet(); Iterator iterator = strings.iterator(); while (iterator.hasNext()){ String next = iterator.next(); String string = jsonObject1.getString(next); System.out.println(next+":"+string); } } }