JSON解析器读取数组

时间:2014-05-23 09:01:07

标签: java json

您好我正在尝试解析看起来像这样的JSONFILE:

"ansible_facts": {
    "ansible_all_ipv4_addresses": [
        "xxx"
    ], 
    "ansible_all_ipv6_addresses": [], 
    "ansible_architecture": "xxx", 
    "ansible_bios_date": "xxx", 
    "ansible_bios_version": "xxx", 
    "ansible_cmdline": {
        "KEYBOARDTYPE": "xx", 
        "KEYTABLE": "xx", 
        "LANG": "xxx", 
        "SYSFONT": "xxx", 
        "crashkernel": "xxx", 
        "elevator": "xxx", 
        "nmi_watchdog": "1", 
        "quiet0": true, 
        "rd_LVM_LV": "xxx", 
        "rd_NO_DM": true, 
        "rd_NO_LUKS": true, 
        "rd_NO_MD": true, 
        "rhgb": true, 
        "ro": true, 
        "root": "xxx", 
        "selinux": "0"

...

这是我的Java程序:

public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try {

        String filePath = "C:\\xxx\\xxx\\xxx\\JSON\\file";

        String file = readFileAsString(filePath);

        JSONObject jsonObject = (JSONObject)parser.parse(file);

        JSONArray ansibleFacts = (JSONArray)jsonObject.get("ansible_facts");

        for (Object o : ansibleFacts)
        {
            JSONObject fact = (JSONObject) o;

            String os = (String) fact.get("ansible_architecture");
            System.out.println(os);

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

            String pythonVersion = (String) fact.get("ansible_python_version");
            System.out.println(pythonVersion);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

}

private static String readFileAsString(String filePath) throws java.io.IOException{
    byte[] buffer = new byte[(int) new File(filePath).length()];
    BufferedInputStream f = null;
    try {
        f = new BufferedInputStream(new FileInputStream(filePath));
        f.read(buffer);
    } finally {
        if (f != null) try { f.close(); } catch (IOException ignored) { }
    }
    return new String(buffer);
}

我得到错误:线程“main”中的异常java.lang.ClassCastException:org.json.simple.JSONObject无法强制转换为org.json.simple.JSONArray。

我的JSON文件直接使用ARRAY启动,我阅读了几篇帖子,但无法理解为什么它不起作用...

1 个答案:

答案 0 :(得分:1)

ansible_facts不是数组,而ansible_all_ipv4_addressesansible_all_ipv6_addresses是数组。

访问特定元素的一些示例:

JSONObject ansibleFacts = jsonObject.getJSONObject("ansible_facts");
String architecture = ansibleFacts.getString("ansible_architecture");
JSONArray ipv4Addresses = ansibleFacts.getJSONArray("ansible_all_ipv4_addresses");
String xxx = ipv4Addresses.getString(0);