9

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 mistake.

Thanks.

Here is my codes to get Json from server:

try {
                String url = String.format(<url here>, province.provinceCode2);
                HttpClient httpClient = getHttpClient();
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity entity = httpResponse.getEntity();
                final String result = EntityUtils.toString(entity);
                parseAndSaveJsonData(province, result);
            } catch (Exception e) {
                e.printStackTrace();
            }

here is codes to parse JsonArray:

String jsonString = <below json string>
JSONArray ja = new JSONArray(jsonString);

Here is my json string:

   [
   {
      "LotPrizes":[
         {
            "Prize":"Giảitám",
            "Range":"50"
         },
         {
            "Prize":"Giảibảy",
            "Range":"264"
         },
         {
            "Prize":"Giảisáu",
            "Range":"3654-5162-3097"
         },
         {
            "Prize":"Giảinăm",
            "Range":"9739"
         },
         {
            "Prize":"Giảitư",
            "Range":"97690-99274-32442-69432-04855-10132-17085"
         },
         {
            "Prize":"Giảiba",
            "Range":"73745-13007"
         },
         {
            "Prize":"Giảinhì",
            "Range":"05521"
         },
         {
            "Prize":"Giảinhất",
            "Range":"74870"
         },
         {
            "Prize":"GiảiDB6",
            "Range":"878833"
         }
      ]
      },
 {
      "LotPrizes":[
         {
            "Prize":"Giảitám",
            "Range":"50"
         },
         {
            "Prize":"Giảibảy",
            "Range":"264"
         },
         {
            "Prize":"Giảisáu",
            "Range":"3654-5162-3097"
         },
         {
            "Prize":"Giảinăm",
            "Range":"9739"
         },
         {
            "Prize":"Giảitư",
            "Range":"97690-99274-32442-69432-04855-10132-17085"
         },
         {
            "Prize":"Giảiba",
            "Range":"73745-13007"
         },
         {
            "Prize":"Giảinhì",
            "Range":"05521"
         },
         {
            "Prize":"Giảinhất",
            "Range":"74870"
         },
         {
            "Prize":"GiảiDB6",
            "Range":"878833"
         }
      ]
      }

    ]
Nguyen Minh Binh
  • 23,891
  • 30
  • 115
  • 165
  • can u show code where u are getting string from server? – ρяσѕρєя K Jan 28 '13 at 16:41
  • It's a JSON "object", not an "array". Unfortunately, some (brain-dead) JSON APIs insist that you know whether it's an object or an array before you parse it, so sometimes you have to see if the first character is `{` or `[`. – Hot Licks Jan 28 '13 at 17:19
  • (You may benefit from studying the [JSON reference manual](http://www.json.org/). Tedious, I know, but I'm confident you can handle it.) – Hot Licks Jan 28 '13 at 17:21
  • wow!!!, you changed JSON String because prev string contain an Json Array as root element and you are doing parsing in right way .you are getting error because somewhere in code you are adding special character in string like when reading from Buffer maybe adding "\n" at the end of string and now current json String contain Json Object – ρяσѕρєя K Jan 28 '13 at 17:21
  • I changed the string to continue discuss With Caerulius. The original string is bound inside [ ] – Nguyen Minh Binh Jan 28 '13 at 17:28
  • @NguyenMinhBinh : great if u solved issue but this is not i think problem solving way to change main idea instead if solving current issue . thanks so much . – ρяσѕρєя K Jan 28 '13 at 17:37
  • @ρяσѕρєя K, please see my update for source codes to get JsonString from server – Nguyen Minh Binh Jan 29 '13 at 02:51
  • I finally found the root cause. Please see my own answer. I think it is a bug of `HttpEntity` – Nguyen Minh Binh Jan 29 '13 at 17:22

3 Answers3

18

This is how to initialize a JSON parser:

JSONObject jsonObject = new JSONObject(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++)
{
  JSONObject curr = 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:

JSONArray jsonArray = null;
String jsonString = <your string>
String currPrize = null;

JSONObject jsonObject = new JSONObject(jsonString);

jsonArray = jsonObject.getJSONArray("data");

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

    for(int j=0; j<currLot.length();j++)
    {
        JSONobject curr = 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.

Caerulius
  • 425
  • 4
  • 21
  • 1
    But, how to get the JsonObject which is parent of "LotPrizes" array?. In my string, this JsonArray has 2 items. – Nguyen Minh Binh Jan 28 '13 at 16:36
  • Simply add a for loop to your logic: for(int i=0;i – Caerulius Jan 28 '13 at 16:39
  • No, The exception is thrown when I try to get the arrays. What I want to ask here is: how to parse the array from json string. Sorry for my limited English Skill – Nguyen Minh Binh Jan 28 '13 at 16:41
  • Check my edits to the answer, I think I made it a bit clearer. – Caerulius Jan 28 '13 at 16:43
  • 1
    Basically, your main problem comes down to the fact that you CANNOT initialize a JSONArray with a string. You must first create it as a JSONObject, and then get a JSONArray from that. – Caerulius Jan 28 '13 at 16:46
  • A new exception: `No value for "LotPrizes"` when I try your solution. That is because `LotPrizes` is grandChild of the root JsonObject. You can paste my json at http://jsonparser.com/ to see it. The root Json Array has 2 items and I want to get 2 that items. – Nguyen Minh Binh Jan 28 '13 at 16:48
  • This seems to be a problem with your JSON formatting. You have blank root nodes connected to children. I assume you are creating the JSON string yourself, and if you are, please read up on JSON format to create correct JSON strings. http://www.w3schools.com/json/default.asp – Caerulius Jan 28 '13 at 16:51
  • No, I don't think the syntax of my Json String wrong. Because the http://jsonparser.com/ can parse it very good. Have any idea? – Nguyen Minh Binh Jan 28 '13 at 16:54
  • It is wrong though, like I said. You need to have every node named, and you do not. The node that contains your "LotPrizes" fields is blank, and cannot be accessed. Name it something like "PrizesList" and then access THAT object through the JSON parser like I showed in my answer. As it stands right now though, that JSON cannot be parsed correctly. – Caerulius Jan 28 '13 at 16:56
  • If you continue having trouble with JSON formatting please make a new question and accept this answer. – Caerulius Jan 28 '13 at 17:01
  • Caerulius, Thank for your time, but it does not helps me resove the issue. I edit the json format as your suggestion but the issue still orrcurs. I think that it's another bug. – Nguyen Minh Binh Jan 28 '13 at 17:10
  • I edited my answer one final time, please tell me if it works. – Caerulius Jan 28 '13 at 17:15
  • I finally found the root cause. Please see my own answer. I think it is a bug of `HttpEntity` – Nguyen Minh Binh Jan 29 '13 at 17:22
2

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

            JSONObject json = new JSONObject(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"));
                }

            }
Harish
  • 3,122
  • 2
  • 31
  • 46
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:

                            HttpClient httpClient = getHttpClient();
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity entity = httpResponse.getEntity();
                InputStream is = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                String json = 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.

IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147
Nguyen Minh Binh
  • 23,891
  • 30
  • 115
  • 165