使用org.JSON解析Java中的JSON
我有一个包含许多JSON对象的大文件,如下所示。我需要解析所有内容,以使用。我无法访问嵌套在“related”中的任何内容 将“一起购买”作为列表检索所需的代码是什么使用org.JSON解析Java中的JSON,java,arrays,json,Java,Arrays,Json,我有一个包含许多JSON对象的大文件,如下所示。我需要解析所有内容,以使用。我无法访问嵌套在“related”中的任何内容 将“一起购买”作为列表检索所需的代码是什么 { "asin": "11158732", "title": "Girls Ballet Tutu Zebra Hot Pink", "price": 3.17, "imUrl": "http://ecx.images-amazon.com/images/I/51fAmVkTbyL._SY300_.jpg",
{
"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程序中进行的,因此某些行可能看起来与上下文无关):
使用以下代码,希望对您有所帮助
//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,key“name”的值是ali,我们称之为 比如: myJsonObject.getString(“名称”)
- 每件事都在[]中,它们将是JSONArray,关系是
索引和值,如:
[“阿里”]
这是一个JsonArray,索引0的值是ali,我们称之为
比如: myJsonArray.getString(0)
请张贴任何样本代码,如果你写了!嗯,我不明白为什么这样不行。我仍然收到
错误:org.json.JSONException:JSONObject[“related”]未找到
您能测试新的并报告结果吗?我尝试了更新的代码,但仍然收到相同的错误错误:org.json.JSONException:JSONObject[“related”]未找到
。这是我用过的一段代码。你在要点上有问题。在第27行:将JSONArray更改为JSONObject,在下一行中就像我的代码一样,JSONArray boutThogether=related.getJSONArray(“一起购买”);哎呀,我在要点上贴错了代码。然而,在进一步的检查中,问题似乎不在代码中,而是在我使用的样本数据集中。我使用-tail创建了一个要测试的示例数据集,没有一个测试对象包含json键“related”,因为它们没有相关的产品。在测试时,我删除了try-catch块(json异常),以查看我收到的json异常错误,所以通常会跳过这些错误。
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");