0

I'm trying to parse json file in my java project using this below code,

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();
}

From above code when i'm using this two below lines

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

Its shows the method getJSONObject(int) is undefined for the type JSONArray

And I'm getting the whole object when using this below code,

System.out.println("Branch are :"+listOfBranches.get(i));

It prints like this,

{"branch_name":"AMM"}

from this I want to get branch name using the key "branch_name". But I could not able to do this because of "the method getJSONObject(int) is undefined for the type JSONArray" exception

And I have added json-simple jar in my project. Could you please suggest me any idea to do this? Thanks in advance.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Olive
  • 149
  • 1
  • 4
  • 13

2 Answers2

2

If i undestood you right then:

 JSONObject item = (JSONObject)listOfBranches.get(0);
 String branchName = (String)item.get("branch_name");
nikelyn
  • 518
  • 3
  • 13
  • Thanks for ur answer. I have used like this for (int i = 0; i < listOfBranches.size(); i++) { JSONObject item = (JSONObject)listOfBranches.get(0); String branchName = (String)item.get("branch_name"); System.out.println("Branch :" + listOfBranches.get(i)+" "+branchName); } I'm getting branch name. but it only prints first branch upto the arraylist size – Olive Oct 31 '17 at 04:22
  • yes i got it by using this JSONObject item = (JSONObject)listOfBranches.get(i); String branchName = (String)item.get("branch_name"); – Olive Oct 31 '17 at 04:23
0

i think you should use org.json instead of simple-json. The method getJSONObject(i) is available in org.json. Refer to the below url for more detail.

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