鍍金池/ 教程/ Java/ Gson樹模型
Gson開發(fā)環(huán)境設(shè)置
Gson數(shù)據(jù)綁定
Gson序列化內(nèi)部類
Gson數(shù)據(jù)流
Gson簡介
Gson對象數(shù)據(jù)綁定
Gson從序列化中排除字段
Gson版本支持
Gson入門程序
Gson類
Gson自定義類型適配器
Gson對象序列化
Gson空對象支持
Gson教程
Gson樹模型
Gson序列化示例

Gson樹模型

樹模型準(zhǔn)備JSON文檔的內(nèi)存樹表示。 它構(gòu)建了一個(gè)JsonObject節(jié)點(diǎn)樹。 這是一種靈活的方法,類似于XML的DOM解析器。

從JSON創(chuàng)建樹

在讀取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