这里例举了2两种不同的json包的使用方式
第一种:
需要用到的依赖:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
String str = "{'a1':1}";
String str1 = "{'b1':2,'b2':3}";
String str2 = "{c:{'c1':4,'c2':5,'c3':6}}";
String str3 = "{d:[7,8,9]}";
// 根据key获取value值
JSONObject json = new JSONObject(str);
System.out.println(json.get("a1"));
// 获取所有的key值
JSONObject json1 = new JSONObject(str1);
JSONArray names = json1.names();
System.out.println(names);
// 遍历所有的key
for (int i = 0; i < names.length(); i++) {
System.out.print(names.getString(i) + " ");
}
System.out.println();
// 遍历所有的value
for (int i = 0; i < names.length(); i++) {
System.out.print(json1.get(names.getString(i)) + " ");
}
System.out.println();
// 获取json中嵌套的json数据
JSONObject json2 = new JSONObject(str2);
JSONObject c = json2.getJSONObject("c");
System.out.println(c);
// 获取josn中嵌套的数组
JSONObject json3 = new JSONObject(str3);
JSONArray d = json3.getJSONArray("d");
System.out.println(d);
// 遍历数组
for (int i = 0; i < d.length(); i++) {
System.out.print(d.get(i) + " ");
}
//补充:.isNull(key)可以判断指定的key的value值是否为空
第二种
需要用到的依赖
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
</dependency>
String str = "{'a1':1}";
String str1 = "{'b1':2,'b2':3}";
String str2 = "{c:{'c1':4,'c2':5,'c3':6}}";
String str3 = "{d:[7,8,9]}";
//根据key获取value值
JSONObject json = JSONObject.fromObject(str);
System.out.println(json.getString("a1"));
//获取所有的key值
JSONObject json1 = JSONObject.fromObject(str1);
JSONArray names = json1.names();
System.out.println(names);
//遍历所有的key
for (int i = 0; i < names.size(); i++) {
System.out.print(names.get(i)+" ");
}
System.out.println();
//遍历所有的value
for (int i = 0; i < names.size(); i++) {
System.out.print(json1.get(names.get(i))+" ");
}
System.out.println();
//获取json中嵌套的json数据
JSONObject json2 = JSONObject.fromObject(str2);
JSONObject c = json2.getJSONObject("c");
System.out.println(c);
//获取josn中嵌套的数组
JSONObject json3 = JSONObject.fromObject(str3);
JSONArray d = json3.getJSONArray("d");
System.out.println(d);
//遍历数组
for (int i = 0; i < d.size(); i++) {
System.out.print(d.get(i)+" ");
}