Skip to content Skip to sidebar Skip to footer

Android - How To Parse Jsonarray From String?

I am trying to parse a json array from json string but it always throws the exception data of type java.lang.String cannot be converted to JSONArray. Please tell me if I make any m

Solution 1:

This is how to initialize a JSON parser:

JSONObject jsonObject = newJSONObject(jsonString);

That will give you the entire string as a Json Object. From there, pull out an individual array as a JsonArray, like this:

JSONArray jsonArray = jsonObject.getJSONArray("LotPrizes");

To access each "LotPrizes" you can use for loop logic:

for(int i=0;i<jsonArray.length();i++)
{
  JSONObjectcurr= jsonArray.getJSONObject(i);

  prize = curr.getString("Prize")

//Do stuff with the Prize String here//Add it to a list, print it out, etc.
}

EDIT: Final code after your JSON edit:

JSONArrayjsonArray=null;
StringjsonString= <your string>
StringcurrPrize=null;

JSONObjectjsonObject=newJSONObject(jsonString);

jsonArray = jsonObject.getJSONArray("data");

for(int i=0;i<jsonArray.length();i++)
{
    JSONArraycurrLot= jsonArray.getJSONObject(i);

    for(int j=0; j<currLot.length();j++)
    {
        JSONobjectcurr= currLot.getJSONObject(j);

        currPrize = curr.getString("Prize");

        //Do something with Prize
    }
}

This code is functional and I'm using an almost identical version in my code. Hope this (finally) works for you.

Solution 2:

Hi @Caerulius, Harish, ρяσѕρєя K, Hot Licks , and all. Finally, after 2 days of headache and 2 sleepless nights, I solved the issue. And because you spend your valued time to discuss with me, I see that I have to tell you the root cause. That's my responsibility.

First of all, I am a senior android developer. So, I at least know about JSON basic, I know how to parse data from JSON string, and I know many useful online tools to validate it. I confirm that the JSON string I got from server is valid.

As I told in my question, I used final String result = EntityUtils.toString(entity); to get JSON string from HttpEntity object. I have used this many times in the past and it worked. No problem. But, in this case, it's not. The original JSON string like this:

   [{
      "LotPrizes":[
         {
            "Prize":"Giảitám",
            "Range":"50"
         },
         {
            "Prize":"Giảibảy",
            "Range":"264"
         },
         ...
    }]

But what I got like this:

"[{
      \"LotPrizes\":[
         {
            \"Prize":\"Giảitám\",
            \"Range\":\"50\"
         },
         {
            \"Prize\":\"Giảibảy\",
            \"Range\":\"264\"
         },
         ...
    }]"

This string is similar with the constant string which we may declare as below:

String stringVariable ="\"[{
          \\\"LotPrizes\\\":[
             {
                \\\"Prize":\\\"Giảitám\\\",
                \\\"Range\\\":\\\"50\\\"
             },
             {
                \\\"Prize\\\":\\\"Giảibảy\\\",
                \\\"Range\\\":\\\"264\\\"
             },
             ...
        }]\" ;

It's a valid string, but not a valid JSON String.

To fix this issue, I change the way to get JSON string, and remove unnecessary characters like this:

HttpClienthttpClient= getHttpClient();
                HttpGethttpGet=newHttpGet(url);
                HttpResponsehttpResponse= httpClient.execute(httpGet);
                HttpEntityentity= httpResponse.getEntity();
                InputStreamis= entity.getContent();
                BufferedReaderreader=newBufferedReader(newInputStreamReader(is, "UTF-8"), 8);
                StringBuildersb=newStringBuilder();
                Stringline=null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                Stringjson= sb.toString();

                json = json.replace("\\", "");
                json = json.substring(1);
                json = json.substring(0, json.length() - 2);

Now, the json variable contain JSON string which I can parse correctly. I think this should a bug of HttpEntity library.

Hope this helps some other guys.

Solution 3:

You can retrieve the jsondata from your string as follows ..

JSONObject json = newJSONObject(jsonString);
            JSONArray jData = json.getJSONArray("data");
            for (int i = 0; i < jData.length(); i++) {
                JSONObject jo = jData.getJSONObject(i);

                JSONArray jLotPrizes = jo.getJSONArray("LotPrizes");
                for (int j = 0; j < jLotPrizes.length(); j++) {
                    JSONObject jobj = jLotPrizes.getJSONObject(j);

                    Log.i("Prize", "" + jobj.getString("Prize"));
                    Log.i("Range", "" + jobj.getString("Range"));
                }

            }

Post a Comment for "Android - How To Parse Jsonarray From String?"