java_in_json
Table of Contents
1 Java 使用 Json
1.1 下载地址:
1.2 构造 json 字符串
JSONObject jsonObject = new JSONObject();jsonObject.put("name", "zhangsan");jsonObject.put("age", 11);JSONArray array = new JSONArray();array.put(0,"lisi");array.put(1,"wangwu");array.put(2,"zhaoliu");jsonObject.put("friends", array);System.out.println(jsonObject.toString());
结果: {"friends":["lisi","wangwu","zhaoliu"],"age":11,"name":"zhangsan"}
1.3 解析 json 字符串
String str = "{\"friends\":[\"lisi\",\"wangwu\",\"zhaoliu\"],\"age\":11,\"name\":\"zhangsan\"}";JSONTokener tokener = new JSONTokener(str);JSONObject object = (JSONObject) tokener.nextValue();System.out.println(object.getString("name"));System.out.println(object.getInt("age"));JSONArray arr = object.getJSONArray("friends");for (int i = 0; i < arr.length(); i++) { String friendName = (String) arr.get(i); System.out.println(friendName);}
结果: zhangsan 11 lisi wangwu zhaoliu
1.4 进一步使用,查看文档.
Created: 2016-04-12 Tue 17:03
24.5.1 ( mode 8.2.10)