java 如何解析json字串
阿新 • • 發佈:2019-01-23
需要的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 ReadJSON {
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 = "{'shu': '2','CHANGE':[{'DETAIL0':[{'XM':'李小明'},{'XM':'李中明'}],'DETAIL1':[{'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();
for(int g=0;g<shu;g++){
StringBuffer kk =new StringBuffer(Integer.toString(g));
JsonArray array2 = subObject.get("DETAIL"+kk.toString()).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();
}
}
}