简体   繁体   English

如何使用简单的 JSON 库读取 json 文件(数组形式)?

[英]How to read json file (array form) using simple JSON library?

Actually, The example below is an answer somewhere in StackOverFlow.实际上,下面的示例是 StackOverFlow 中某处的答案。 I tried to use the below code, but,我尝试使用下面的代码,但是,

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

Above line doesn't work because of the below Exception.由于以下异常,上面的行不起作用。

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

Is there any way to read my JSON file?有什么方法可以读取我的 JSON 文件吗?

JSON file: JSON 文件:

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

Java code:爪哇代码:

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 + "");
    }
  }

The exception is quite clear.例外很明显。 You need to cast to JSONObject and not JSONArray您需要转换为JSONObject而不是JSONArray

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

You could possibly have this structure for your JSON:您的 JSON 可能具有以下结构:

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

Now to iterate you can do:现在要迭代,您可以执行以下操作:

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 + "");
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM