需要的jar:gson-2.1.jar gson-2.1-javadoc.jar gson-2.1-sources.jar
package jiexixml;
import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
public class ReadJSON1 {
public static void main(String args[]){
try {
JsonParser parser=new JsonParser(); //创建JSON解析器
//String json = "{'name': '亲亲宝宝','array':[{'a':'111','b':'222','c':'333'},{'a':'','b':'','c':''},{'a':'','b':'','c':''}],'address':'亲亲宝宝','CHANGE':['DETAIL':[{'XM':'陈大发'},{'XM':'陈小发'}],'DETAIL':[{'XM':'李小明'}]]}";
String json = "{'CHANGE':[{'DETAIL':[{'XM':'李小明'},{'XM':'李中明'}]},{'DETAIL':[{'XM':'李大明'}]}]}";
JsonObject object=(JsonObject) parser.parse(json);
//JsonObject object=(JsonObject) parser.parse(new FileReader("test.json")); //创建JsonObject对象
/* System.out.println("cat="+object.get("name").getAsString()); //将json数据转为为String型的数据
//System.out.println("pop="+object.get("pop").getAsBoolean()); //将json数据转为为boolean型的数据
JsonArray array=object.get("array").getAsJsonArray(); //得到为json的数组
for(int i=0;i<array.size();i++){
System.out.println("---------------");
JsonObject subObject=array.get(i).getAsJsonObject();
System.out.println("id="+subObject.get("a").getAsString());
System.out.println("name="+subObject.get("b").getAsString());
System.out.println("ide="+subObject.get("c").getAsString());
}*/
//int shu =Integer.parseInt(object.get("shu").getAsString());
JsonArray array1=object.get("CHANGE").getAsJsonArray(); //得到为json的数组
for(int i=0;i<array1.size();i++){
System.out.println("---------------");
JsonObject subObject=array1.get(i).getAsJsonObject();
System.out.println(subObject.toString());
JsonArray array2 = subObject.get("DETAIL").getAsJsonArray();
for(int t=0;t<array2.size();t++){
JsonObject subObject1=array2.get(t).getAsJsonObject();
System.out.println("id="+subObject1.get("XM").getAsString());
}
}
} catch (JsonIOException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
}