2015-11-08 68 views
1

我有一個JSON如下面如何使用GSON從JSON樹

{ 
    "apiVersion": "v1", 
    "metadata": { 
     "status": { 
      "statusCode": 0 
     }, 
    }, 
    "stuff": [ 
     { 
      "name": { 
       "text": "red" 
      }, 
      "properties": [ 
       { 
        "attributes": { 
         "shade": "dark" 
        }, 
        "component": { 
         "id": "BA1", 
        } 
        "type": "Color" 
       } 
      ] 
     }, 
     { 
      "name": { 
       "text": "Toyota Camry" 
      }, 
      "properties": [ 
       { 
        "attributes": {}, 
        "component": { 
         "id": "MS", 
        }, 
        "type": "Vehicle" 
       } 
      ] 
     }, 
    ] 
} 

我使用GSON解析的結果是這樣獲得的JSON值:

Gson gson = new Gson(); 
JsonObject json = (JsonObject) gson.fromJson(in, JsonObject.class); 
System.out.println(json.get("apiVersion").getAsString()); 

我可以得到apiVersion,但不知道如何獲取json樹中的元素。例如,type ......如果我要輸出所有不同type ..in這種情況下Color and Vehicle

+0

你的JSON字符串無效'}},'檢查的StatusCode後, – rajuGT

+0

對不起,我只是用它作爲一個例子來傳達出點。 – Anthony

回答

0

我必須在這裏失去一些東西,但爲什麼你不能呼叫getJsonObject?例如,要獲得狀態代碼:

System.out.println(json.getAsJsonObject("metadata") 
         .getAsJsonObject("status") 
         .get("statusCode").getAsInt()); 
0

您可以在這個問題上創建一個對象,並解析JSON到它(與GSON):

ParsedObject parsedObject = new Gson().fromJson(json, ParsedObject.class); 

public class ParsedObject { 

    @SerializedName(value = "apiVersion") 
    private String mApiVersion; 

@SerializedName(value = "metadata") 
    private Metadata mMetadata; 

} 
+0

如果我不想創建課程,該怎麼辦。我將只使用這一次使用。 – Anthony