package com.lijian.test.josn;
import java.io.FileNotFoundException;
import java.io.FileReader;
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;
/**
* 使用JAVA读取JSON数据
* @author Android
*
*/
public class ReadJosn {
public static void main(String[] args) {
try {
//创建解析器
JsonParser parser = new JsonParser();
//创建JSON对象
JsonObject object = (JsonObject) parser.parse(new FileReader("test.json"));
//读取键值对
System.out.println("cat=" +object.get("cat").getAsString());
System.out.println("pop=" +object.get("pop").getAsBoolean());
//读取数组中的数据
JsonArray array = object.get("languages1").getAsJsonArray();
//用for循环来读取数组中的数据
for (int i = 0; i < array.size(); i++) {
System.out.println("-------");
JsonObject subObject = array.get(i).getAsJsonObject();
System.out.println("id=" +subObject.get("id").getAsInt());
System.out.println("score=" +subObject.get("score").getAsString());
System.out.println("name=" +subObject.get("name").getAsString());
}
} catch (JsonIOException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
//test.json文档
test.json
{ "cat":"it", "languages1":[ {"id":1,"ide":"Eclipse","name":"Java"}, {"id":2,"ide":"XCode","name":"Swift"}, {"id":3,"ide":"Visual Studio","name":"C#"} ], "pop":true }