Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONArray does not work when I am getting the JSON string from the server

Tags:

java

json

android

I've looked up some answers but am not sure why mine is failing exactly...

The code looks something like this

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        String json = EntityUtils.toString(httpEntity);

        //Convert to JsonArray
        JSONArray jsonArray = new JSONArray(json);

        Log.i(DEBUG_TAG, Integer.toString(jsonArray.length()));

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Log.i(DEBUG_TAG, jsonObject.getString(KEY_ID));

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            // adding each child node to HashMap key => value
            map.put(KEY_ID, jsonObject.getString(KEY_ID));
            map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
            map.put(KEY_ARTIST, jsonObject.getString(KEY_ARTIST));
            map.put(KEY_DURATION, jsonObject.getString(KEY_DURATION));
            map.put(KEY_VOTECOUNT, jsonObject.getString(KEY_VOTECOUNT));
            map.put(KEY_THUMB_URL, jsonObject.getString(KEY_THUMB_URL));
            map.put(KEY_GENRE, jsonObject.getString(KEY_GENRE));

            //Adding map to ArrayList
            if (Integer.parseInt(jsonObject.getString(KEY_VOTECOUNT)) == -1){
                //If VoteCount is -1 then add to header
                headerList.add(map);
            }else {
                songsList.add(map);
            }
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

When I run logcat on String json, it seems to show correct info which is kind of like this...

  {
"userdata": [
    {
        "id": "8",
        "title": "Baby One More Time",
        "artist": "Britney Spears",
        "duration": "03:24:00",
        "votes": "0",
        "thumb_url": "http://api.androidhive.info/music/images/dido.png",
        "genre": null
    },
    {
        "id": "2",
        "title": "As Long As You Love Me",
        "artist": "Justin Bieber",
        "duration": "05:26:00",
        "votes": "0",
        "thumb_url": "http://api.androidhive.info/music/images/enrique.png",
        "genre": "Rock"
    }
]
}

and the logcat on

JSONArray jsonArray = new JSONArray(json);

tells me that jsonArray.length()

10-31 22:57:28.433: W/CustomizedListView(26945): error! Invalid index 0, size is 0

Please let me know

Thank you,

like image 858
Taehoon A Kim Avatar asked Nov 03 '22 12:11

Taehoon A Kim


1 Answers

The problem is it's not a JSON Array. It's a JSON object, JSON array starts with a [ and ends with a ]

enter image description here

and JSON object starts with a { and end with a }

enter image description here

for further reference you can see it here -> http://www.json.org/

to fix it you should convert your json string to json object first then parse the json object to get the json array

this is an example of parsing json array from jsonobject

void ParseAPIWithJSON()
    {
     String readGooglePlace = readGooglePlaceAPI();
     try
     {

      InputStream is = new ByteArrayInputStream(readTwitterFeed.getBytes("UTF-8"));
      byte [] buffer = new byte[is.available()];
      while (is.read(buffer) != -1);
      String jsontext = new String(buffer);
      JSONObject entries = new JSONObject(jsontext);

      JSONArray hasil = entries.getJSONArray("results");
      results = hasil.getString(o);
      Log.i("TAG", results);
      int i;
      Log.i("TAG", Integer.toString(hasil.length()));
      numberofPlaces = hasil.length();
      for (i=0;i<hasil.length();i++)
      {
       JSONObject data = hasil.getJSONObject(i);
       namePlaces[i] = data.getString("name");
       Log.i("TAG", namePlaces[i]);
       JSONObject geometry = data.getJSONObject("geometry");
       JSONObject location = geometry.getJSONObject("location");
       latPlaces[i] = location.getDouble("lat");
       longPlaces[i] = location.getDouble("lng");
       Log.i("TAG", "Lat : "+latPlaces[i]+" Long : "+longPlaces[i]);
         }

     }
     catch (Exception je)
     {
      Log.e("TEST1", je.getMessage());
     }
    }

from that whole code I think you only need to understand this

 String jsontext = new String(buffer);
 JSONObject entries = new JSONObject(jsontext);
 JSONArray hasil = entries.getJSONArray("results");

convert string->jsonobject->jsonarray->get value

like image 170
Niko Adrianus Yuwono Avatar answered Nov 12 '22 17:11

Niko Adrianus Yuwono