樹模型準(zhǔn)備JSON文檔的內(nèi)存樹表示。 它構(gòu)建了一個(gè)JsonObject節(jié)點(diǎn)樹。 這是一種靈活的方法,類似于XML的DOM解析器。
在讀取JSON之后,JsonParser
提供了一個(gè)指向樹的根節(jié)點(diǎn)的指針。根節(jié)點(diǎn)可以用來遍歷整個(gè)樹。 考慮下面的代碼片段來獲取提供的JSON字符串的根節(jié)點(diǎn)。
//Create an JsonParser instance
JsonParser parser = new JsonParser();
String jsonString =
"{\"name\":\"Maxsu\", \"age\":26,\"verified\":false,\"marks\": [100,90,85]}";
//create tree from JSON
JsonElement rootNode = parser.parse(jsonString);
在遍歷樹并處理數(shù)據(jù)時(shí),使用到根節(jié)點(diǎn)的相對路徑獲取每個(gè)節(jié)點(diǎn)。 以下代碼片段顯示了如何遍歷樹。
JsonObject details = rootNode.getAsJsonObject();
JsonElement nameNode = details.get("name");
System.out.println("Name: " +nameNode.getAsString());
JsonElement ageNode = details.get("age");
System.out.println("Age: " + ageNode.getAsInt());
示例
創(chuàng)建一個(gè)名為GsonTester
的Java類文件,如下代碼實(shí)現(xiàn):GsonTester.java -
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
public class GsonTester {
public static void main(String args[]) {
String jsonString =
"{\"name\":\"Maxsu\", \"age\":26,\"verified\":false,\"marks\": [100,90,85]}";
JsonParser parser = new JsonParser();
JsonElement rootNode = parser.parse(jsonString);
if (rootNode.isJsonObject()) {
JsonObject details = rootNode.getAsJsonObject();
JsonElement nameNode = details.get("name");
System.out.println("Name: " +nameNode.getAsString());
JsonElement ageNode = details.get("age");
System.out.println("Age: " + ageNode.getAsInt());
JsonElement verifiedNode = details.get("verified");
System.out.println("Verified: " + (verifiedNode.getAsBoolean() ? "Yes":"No"));
JsonArray marks = details.getAsJsonArray("marks");
for (int i = 0; i < marks.size(); i++) {
JsonPrimitive value = marks.get(i).getAsJsonPrimitive();
System.out.print(value.getAsInt() + " ");
}
}
}
}
執(zhí)行上面示例代碼,得到以下結(jié)果 -
Name: Maxsu
Age: 26
Verified: No
100 90 85