getJSONObject无法在Java

时间:2017-10-30 14:43:27

标签: java json

我试图使用下面的代码解析我的java项目中的json文件,

JSONParser parser = new JSONParser();

try {
    Object obj = null;
    try {
        obj = parser.parse(new FileReader(new File("json/branch_list.json")));
    } catch (org.json.simple.parser.ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    JSONObject jsonObject = (JSONObject) obj;
    System.out.println("Branches are :");
    JSONArray listOfBranches = (JSONArray) jsonObject.get("branch_list");
    Iterator iterator = listOfBranches.iterator();

    for (int i = 0; i < listOfBranches.size(); i++) {
        JSONObject c = listOfBranches.getJSONObject(i);
        System.out.println("Branch are :" + listOfBranches.get(i));
    }

    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

从上面的代码中,当我使用以下两行

JSONObject c = listOfBranches.getJSONObject(i);
String branchName = c.getString("branch_name");

它显示方法getJSONObject(int)未定义类型JSONArray

我在使用以下代码时获得了整个对象,

System.out.println(&#34;分支是:&#34; + listOfBranches.get(i));

它打印得像这样,

{&#34; branch_name&#34;:&#34; AMM&#34;}

从此我想使用密钥&#34; branch_name&#34; 获取分支名称。但我无法做到这一点,因为&#34;方法getJSONObject(int)未定义类型JSONArray&#34;例外

我在项目中添加了json-simple jar。你能建议我这么做吗?提前谢谢。

2 个答案:

答案 0 :(得分:0)

如果我当时不知道你:

 JSONObject item = (JSONObject)listOfBranches.get(0);
 String branchName = (String)item.get("branch_name");

答案 1 :(得分:-1)

我认为你应该使用org.json而不是simple-json。方法getJSONObject(i)在org.json中可用。有关更多详细信息,请参阅以下网址。

https://stackoverflow.com/questions/2591098/how-to-parse-json