我有一个包含许多JSON对象的大文件,如下所示。我需要使用org.json library将所有内容解析为数组形式的"bought_together“项。我在访问嵌套在"related“中的任何内容时遇到了问题。
以列表形式检索"bought_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"));发布于 2016-11-07 06:44:41
使用下面的代码,我希望能对你有所帮助。
//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");-更新
我认为你需要做到这一点(这不是技术上的区别,所有的区别都是)
{"name":"ali"}
这是一个jsonobject,key "name“的值是ali,我们这样命名它:
myJsonObject.getString("name");
“阿里”
这是一个JsonArray,索引0的值是ali,我们称之为
像这样:
myJsonArray.getString(0);
所以在你的例子中:
关键字仍然是JSONObject
https://stackoverflow.com/questions/40455305
复制相似问题