【问题标题】:How to read json file (array form) using simple JSON library?如何使用简单的 JSON 库读取 json 文件(数组形式)?
【发布时间】:2014-07-22 12:30:45
【问题描述】:

实际上,下面的示例是 StackOverFlow 中某处的答案。 我尝试使用下面的代码,但是,

JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));

由于以下异常,上述行不起作用。

java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray

有什么方法可以读取我的 JSON 文件吗?

JSON 文件:

[
    {
        "name": "John",
        "city": "Berlin",
        "cars": [
            "audi",
            "bmw"
        ],
        "job": "Teacher"
    },
    {
        "name": "Mark",
        "city": "Oslo",
        "cars": [
            "VW",
            "Toyata"
        ],
        "job": "Doctor"
    }
]

Java 代码:

JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));

for (Object o : a) {
    JSONObject person = (JSONObject) o;

    String name = (String) person.get("name");
    System.out.println(name);

    String city = (String) person.get("city");
    System.out.println(city);

    String job = (String) person.get("job");
    System.out.println(job);

    JSONArray cars = (JSONArray) jsonObject.get("cars");

    for (Object c : cars) {
      System.out.println(c + "");
    }
  }

【问题讨论】:

  • 文件中说没有数组,只有一个简单的json对象。
  • 先去json.org学习一下JSON语法。只需 5-10 分钟。
  • (就是说文件中的数据不是数组。也就是说,你上面显示的不是文件中的数据。)

标签: java arrays json


【解决方案1】:

例外情况很明显。 您需要转换为 JSONObject 而不是 JSONArray

JSONObject a = (JSONObject) parser.parse(new FileReader("c:\\exer4-courses.json"));

您的 JSON 可能具有这种结构:

{
   "records": [
      {
         "name": "John",
         "city": "Berlin",
         "cars": [
            "audi",
            "bmw"
         ],
         "job": "Teacher"
      },
      {
         "name": "Mark",
         "city": "Oslo",
         "cars": [
            "VW",
            "Toyata"
         ],
         "job": "Doctor"
      }
   ]
}

现在进行迭代,您可以这样做:

JSONArray records = (JSONArray)a.get("records");

for (Object o : records) {
    JSONObject person = (JSONObject) o;

    String name = (String) person.get("name");
    System.out.println(name);

    String city = (String) person.get("city");
    System.out.println(city);

    String job = (String) person.get("job");
    System.out.println(job);

    JSONArray cars = (JSONArray) jsonObject.get("cars");

    for (Object c : cars) {
      System.out.println(c + "");
    }
  }

【讨论】:

  • 这意味着引用的 JSON 不是文件中的实际内容。
猜你喜欢
  • 2012-06-11
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多