【问题标题】:Parsing JSON in Java Using org.json使用 org.json 在 Java 中解析 JSON
【发布时间】:2016-11-06 22:32:35
【问题描述】:

我有一个包含许多类似于以下内容的 JSON 对象的大文件。我需要使用org.json library 解析所有内容以将“bought_together”项目作为数组获取。我无法访问嵌套在“相关”中的任何内容。

检索“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"));

【问题讨论】:

  • 如果您写过任何示例代码,请发布!

标签: java arrays json


【解决方案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 和关系 是键和值:

    {"name":"ali"}

    这是一个jsonobject,键“name”的值是ali,我们称之为 喜欢:

    myJsonObject.getString("name");

  • 一切都在 [] 中,它们将是 JSONArray 并且关系是 索引和值如:

    [“阿里”]

    这是一个JsonArray,索引0的值为ali,我们称之为
    喜欢:

    myJsonArray.getString(0);

所以在你的情况下:

  1. 您的总对象是 JSONObject
  2. “相关”键的值仍然是 JSONObject
  3. “bought_together”键的值(在 {jsonobject}“相关”键的值内)是一个 JSONArray

【讨论】:

  • 嗯,我不明白为什么这不起作用。我仍然收到Error: org.json.JSONException: JSONObject["related"] not found
  • 你能测试新的并报告结果吗?
  • 我尝试了更新的代码,但仍然收到相同的错误Error: org.json.JSONException: JSONObject["related"] not found。这是我使用的代码的gist
  • 您的要点有问题。在第 27 行:将 JSONArray 更改为 JSONObject,并在下一行中像我的代码一样操作 JSONArray boutThogether = related.getJSONArray("bought_together");
  • 糟糕,我在要点上发布了错误的代码。然而,经过进一步检查,问题似乎并不存在于代码中,而是在我使用的示例数据集中。我使用 -tail 创建了一个示例数据集以进行测试,并且没有一个测试对象包含 json 键“相关”,因为它们没有相关产品。测试时,我删除了我的 try catch 块(json 异常)以查看我收到了哪些 json 异常错误,所以通常这些会被跳过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多