0

I have JSON file content as the following details:

{"name":"abg","phone":["12313","4654654","4546"],"city":"NY"}
{"name":"jea","phone":["8941","978","`13421","45231"],"city":"LA"}

To parse the file I used this code:

                  String var1 = output;
                   JSONObject obj;
                   try {
                          obj = new JSONObject(var1);
                          String a = obj.getString("name");
                          String b = obj.getString("phone");
                          String c = obj.getString("city");

                          System.out.println("name:" + a);
                          System.out.println("phone:" + b);
                          System.out.println("city:" + c);}

How can I parse the phone ?

eyal1506
  • 113
  • 2
  • 5
  • 11
  • 2
    Possible duplicate of [Accessing members of items in a JSONArray with Java](https://stackoverflow.com/questions/1568762/accessing-members-of-items-in-a-jsonarray-with-java) – vahdet Jun 13 '18 at 07:47

3 Answers3

0

You can use something like below:

obj = new JSONObject(var1);
JSONArray jsonArr = obj.getJSONArray("phone");

for(int i=0; i<jsonArr.length();i++) {
    System.out.println(jsonArr.get(i));
}
Deepak Sharma
  • 456
  • 4
  • 15
0

You can make use of JSONObject and JSONArray classes of org.json package as shown below:

    JSONObject obj = new JSONObject("{\"name\":\"abg\",\"phone\":[\"12313\",\"4654654\",\"4546\"],\"city\":\"NY\"}");

    JSONArray array = obj.getJSONArray("phone");
    for(int i=0; i<array.length();i++) {
        System.out.println(array.get(i));
    }
Yug Singh
  • 3,112
  • 5
  • 27
  • 52
0
obj = new JSONObject(var1);
//other objects
JsonArray jsonArr = obj.getJsonArray("phone");

for(obj:jsonArr){
  System.out.println("phone:" + obj);
}