0

I am trying to parse a JsonArray and get its values but I am gettign error when I use

   jitem.getString("firstitem"); 

or

  jitem.getJSONObject("firstitem");

or

 jitem.get("firstitem");

Following is the code snippet.

  JSONArray arr_items = new JSONArray(str); 
        if(arr_items!=null && arr_items.size()>0){

            for(int i=0;i<arr_items.size();i++){
            JSONObject jitem = arr_items.getJSONObject(i);//works fine till here
             jitem.getString("firstitem"); //throws exception here
            }

This is the JSONArray that I am parsing

 [{"firstitem":"dgfd","secondtitem":"dfgfdgfdg","thirditem":"fdgfdgdf@sjhasjkdsha.com","fourthitem":"jkksdjklsfjskj"}]

what I am doing wrong? How to get these values by using keys?

Update:Note This array and its parameters are not null at all. They all have valid values.

Just_another_developer
  • 5,737
  • 12
  • 50
  • 83

2 Answers2

0

First check arr_items is not empty. Then, try surrounding your snippet with try/catch :

try {
       your snippet

      } catch (JSONException e) {
          e.printStackTrace();
      }
RockDaFox
  • 217
  • 2
  • 9
  • How does this solve the problem? It avoids an exception, but one still does not have the value. – Henry May 04 '17 at 11:44
  • In Android Studio if i don't surround with try/catch this type of snippet, the editor give an alert and i must surround it. So maybe, he can try – RockDaFox May 04 '17 at 12:03
0

Check below

String json ="{'array':" + "[{'firstitem':'dgfd','secondtitem':'dfgfdgfdg','thirditem':'fdgfdgdf@sjhasjkdsha.com','fourthitem':'jkksdjklsfjskj'}]"+ "}";
     JSONObject myjson = new JSONObject(json);
    JSONArray the_json_array = myjson.getJSONArray("array");

    int size = the_json_array.length();
//  ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
    //  arrays.add(another_json_object);
        System.out.println(another_json_object.get("firstitem"));
    }

it require some array name so appended array name to it , if you want without it you have to add GSON.

gladiator
  • 1,249
  • 8
  • 23