2016-11-06 113 views
0

我有一個很大的文件,其中包含許多與以下類似的JSON對象。我需要解析所有的東西,使用org.json library作爲數組來獲得「buying_together」項。我無法訪問嵌套在「相關」中的任何內容。使用org.json解析Java中的JSON

將「buying_together」作爲列表檢索所需的代碼是什麼?

{ 
    "asin": "11158732", 
    "title": "Girls Ballet Tutu Zebra Hot Pink", 
    "price": 3.17, 
    "imUrl": "http://ecx.images-amazon.com/images/I/51fAmVkTbyL._SY300_.jpg", 
    "related": 
    { 
    "also_bought": ["L00JHONN1S", "B002BZX8Z6"], 
    "also_viewed": ["F002BZX8Z6", "B00JHONN1S", "B008F0SU0Y", "B00D23MC6W", "B00AFDOPDA"], 
    "bought_together": ["D202BZX8Z6"] 
    }, 
    "salesRank": {"Toys & Games": 211836}, 
    "brand": "Coxlures", 
    "categories": [["Sports & Outdoors", "Other Sports", "Dance"]] 
} 

這是我嘗試(請注意,這是一個MapReduce的程序,所以一些線似乎斷章取義之內。):

JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line 
JSONArray boughtTogether = new JSONArray(object.getJSONArray("bought_together")); 
+2

請寫任何示例代碼,如果你寫了! – iNan

回答

1

使用下面的代碼,我希望它幫你。

//this will be your json object that contains and convert your string to jsonobject 
//if you have json object already skip this. 
JSONObject yourJSON = new JSONObject(targetString); 

//getting the "related" jsonObject 
JSONObject related = yourJSON.getJSONObject("related"); 

//getting the "bought_together" as an jsonArray and do what you want with it. 
//you can act with jsonarray like an array 
JSONArray bought_together = related.getJSONArray("bought_together"); 


//now if you run blow code 

System.out.print(bought_together.getString(0)); 

//output is : D202BZX8Z6 

-------根據更新的問題------ 你應該改變你這樣的代碼更新:

JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line 

JSONObject related = object.getJSONObject("related"); 

JSONArray boughtTogether = related.getJSONArray("bought_together"); 

-------更新-------

我認爲你需要這一點(它不是技術性所有的他們差

  • 每一件事情都在{},他們會的JSONObject和關係 是關鍵和價值,如:

    {「名」:「阿里」}

    這是一個JSONObject和關鍵的價值「名稱「是阿里,我們把它叫做 like:

    myJsonObject.getString(」name「);

  • 每一件事情是在[]中,它們將是JSONArray和的關係是 索引和值等:

    [「阿里」]

    這是一個JsonArray索引0的值是阿里我們稱之爲
    like:

    myJsonArray.getString(0);

所以你的情況:

  1. 您的總目標是一個JSONObject
  2. 的 「相關」 的價值關鍵還是是一個JSONObject
  3. 的 「bought_together」 鍵的值(其是在{jsonobject}「related」鍵的值內)是一個JSONArray
+0

嗯,我不明白爲什麼這不起作用。我仍然得到'錯誤:org.json.JSONException:JSONObject [「related」]找不到' –

+0

你能測試新的並報告結果嗎? –

+0

我試過更新的代碼,仍然收到錯誤'錯誤:org.json.JSONException:JSONObject [「related」] not found'。這是我使用的代碼[gist](https://gist.github.com/anonymous/9ec90dff79e824361ea5892aa9b936b5)。 –