【问题标题】:JSON Parsing through all elements in Java using the org.json library?JSON 使用 org.json 库解析 Java 中的所有元素?
【发布时间】:2021-08-11 14:18:17
【问题描述】:

我正在尝试解析 json 文件中的所有记录。我目前有 3 条记录,每条记录中有 20 个不同的对象。当我执行以下功能时,它只抓取第一个元素和其中的对象,我如何继续从 json 文件中抓取其他元素。这是我正在使用的。

// Read from JSON file using the readallBytes method and put it in the contents variable
String contents = new String((Files.readAllBytes(Paths.get(first))));

// Create JSON object to put the contents into it to look up keys for easy data extraction
JSONObject o = new JSONObject(contents);

我注意到 content 变量确实显示了所有 3 个元素,但是一旦将其放入 JSONObject 中,它只需要第一个元素。需要找出如何遍历其余 3 个元素。 json 文件的格式如下:

任何帮助都非常感谢。

{
  "id": 117,
  "name": "Table Rock Sheet",
  "type": "physical",
  "sku": "JDE1353",
  "description": "<p><\/p>",
  "weight": 0.3,
  "width": 3,
  "depth": 3,
  "height": 1,
  "price": 8.6,
  "cost_price": 0,
  "retail_price": 5.99,
  "sale_price": 8.69,
  "map_price": 0,
  "tax_class_id": 0,
  "product_tax_code": "",
  "calculated_price": 8.69,
  "categories": [
    33
  ]
},
{
  "id": 118,
  "name": "Car Jack Stand",
  "type": "physical",
  "sku": "35353",
  "description": "<p><\/p>",
  "weight": 0.3,
  "width": 3.25,
  "depth": 3.75,
  "height": 0.25,
  "price": 8.6,
  "cost_price": 0,
  "retail_price": 5.99,
  "sale_price": 8.69,
  "map_price": 0,
  "tax_class_id": 0,
  "product_tax_code": "",
  "calculated_price": 8.69,
  "categories": [
    35,
    39,
    42
  ]
},
{
  "id": 119,
  "name": "Wildlife Painting Portrate",
  "type": "physical",
  "sku": "TER35333",
  "description": "<p><\/p>",
  "weight": 0.3,
  "width": 0.25,
  "depth": 3.25,
  "height": 3.75,
  "price": 7.92,
  "cost_price": 0,
  "retail_price": 4.99,
  "sale_price": 8,
  "map_price": 0,
  "tax_class_id": 0,
  "product_tax_code": "",
  "calculated_price": 8,
  "categories": [
    35,
    39,
    42
  ]
}

【问题讨论】:

    标签: java json org.json


    【解决方案1】:

    您的内容不是有效的 JSON。它是 3 个 JSON 对象的序列,它们没有排列在 JSON 数组中。那么,你阅读你的内容并解析一个对象会发生什么。它完成读取完整的 JSON 对象并停止。如果要将文件更改为有效的 JSON,则需要将其括在方括号中。[...]。将其读取为 JSONArray。它会将其读取为包含 3 个 JSONObjects 的 JSONArray。
    另外我建议从 org.json 库切换到 Jackson-JSON,也称为 Faster-XML。事实上的标准 JSON 库。 (或基于 Jackson-JSON 的 Google 的 Gson)。请参阅 Jackson 主页 here 教程 - here、Maven 工件 - here 和 ObjectMapper 类的 javadoc - here。在该类中,请参阅方法 readValue(...)writeValueAsString(...)

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多