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

时间:2014-07-22 12:30:46

标签: java arrays json

实际上,下面的示例是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 + "");
    }
  }

1 个答案:

答案 0 :(得分:0)

异常非常清楚。 您需要转为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 + "");
    }
  }