2016-11-06 69 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)。 –