如何使用简单的JSON库读取JSON文件(数组形式)? [英] How to read json file (array form) using simple JSON library?

查看:297
本文介绍了如何使用简单的JSON库读取JSON文件(数组形式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,以下示例是StackOverFlow中某个地方的答案。
我尝试使用以下代码,但是

Actually, The example below is an answer somewhere in 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

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

Is there any way to read my JSON file?

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


推荐答案

异常很明显。
您需要转换为 JSONObject 而不是 JSONArray

The exception is quite clear. You need to cast to JSONObject and not JSONArray

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

您可能对JSON具有以下结构:

You could possibly have this structure for your 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库读取JSON文件(数组形式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆