2014-11-22 67 views
0

我想用java GSON解析來自JSON數據我有此JSON解串器的Json與GSON在Java中

{ 
     "time": 3.251, 
     "about_us": { 
     "dc:identifier": "some string", 
     "dc:title": "some string", 
     "dc:contributor": [ 
      "1", 
      "2" 
     ], 
     "dc:hasversion": "some string" 
     }, 
     "results": { 
     "ocw": [ 
      { 
      "title": "some string", 
      "url": "some string", 
      "language": "some string", 
      "university_name": "some string", 
      "university_url": "some string", 
      "description": "", 
      "uri": "some string5", 
      "similar": "some string", 
      "resourceType": "OCW", 
      "relatedoers": [ 

        ] 
      } 
     ], 
     "otheroer": [ 

     ] 
     } 
    } 

我只需要得到"ocw"場,我很困惑如何做到這一點。 我爲json對象創建了相應的java類,並使用@SerializedName註釋來指定要爲每個數據成員抓取的字段名稱。

這些類如下。

結果

OCW

+0

你對這個發現有什麼研究到目前爲止還是你嘗試過的代碼?那裏應該有很多例子。 – mdnghtblue 2014-11-22 21:10:48

+0

「ocw」不是一個字段。 – 2014-11-22 22:58:26

+0

[如何解析Java中的JSON]可能的重複(http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – 2014-11-23 23:39:26

回答

1

如果你有這樣的json存儲在某些jsonString

JsonObject jsonObject = (JsonObject) new JsonParser().parse(jsonString); 
    JsonElement jsonElement = jsonObject.getAsJsonObject("results").getAsJsonArray("ocw").get(0); 
    MyObject object = new GsonBuilder().create().fromJson(jsonElement, MyObject.class);  

爲MyObject應反映這一部分:

 "title": "some string", 
     "url": "some string", 
     "language": "some string", 
     "university_name": "some string", 
     "university_url": "some string", 
     "description": "", 
     "uri": "some string5", 
     "similar": "some string", 
     "resourceType": "OCW", 
     "relatedoers": [ 

       ]