2

I've spent 2 days to find a solution with of problem.

Here is the error:

E/log_tag: Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray

Here is JSON:

[
{
    "Id": "5207fc6473516724343ce7a5",
    "Name": "Эриван",
    "Types": [
        "Ресторан"
    ],
    "Latitude": 53.904752,
    "Longitude": 27.521095,
    "OperatingTime": [
        {
            "Day": 1,
            "Start": "10:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 2,
            "Start": "10:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 3,
            "Start": "10:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 4,
            "Start": "10:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 5,
            "Start": "10:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 6,
            "Start": "08:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 0,
            "Start": "08:00:00",
            "Finish": "23:00:00"
        }
    ],
    "IsBookingAvailable": false
}]

Class for getting String value:

 public class JSONGet {

    public static String getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        // Download JSON data from URL
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

        // Convert response to string
        try{
            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();
            result = sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }

        try{

            jArray = new JSONArray(result);
        }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
        }

        return result;
    }
  }

And here is converting to JSONArray:

String jsonObjRecv = JSONGet.getJSONfromURL(URL_LIST);

JSONArray jsonArr = new JSONArray(jsonObjRecv);

I was trying to get Json object then convert it into Json array but I received the same error.

11
  • your json is malformed. write it to a file and check Commented Aug 11, 2013 at 16:27
  • @DevZer0 Where? It looks fine to me and jsonlint.com says it's valid. Commented Aug 11, 2013 at 16:42
  • If you print out the String before you try and put it into the JSONArray, is it exactly the same as the file? Commented Aug 11, 2013 at 16:44
  • 1
    @MrLore well you get java.lang.String cannot be converted to JSONArray when json is invalid. there has to be something like a hidden char there Commented Aug 11, 2013 at 16:44
  • 1
    Are you sure the response from the request is encoded to iso-8859-1 and not some other encoding? Commented Aug 11, 2013 at 16:45

4 Answers 4

3

The problem is that your JSON is in the incorrect format. I have tried with your sample JSON and found the solution to it. Now the inbuilt JSONObject and JSONArray cannot be used to get such a json response.

You need to add json-simple library to your project by adding it to gradle:

implementation 'com.googlecode.json-simple:json-simple:1.1.1'

Or download the library "json-simple-1.1.1.jar" from this link https://repo1.maven.org/maven2/com/googlecode/json-simple/json-simple/1.1.1/json-simple-1.1.1.jar

Then you can parse your JSON easily and it won't give any error. I have made a small sample code for you on how to use it :

import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;

JSONParser parser_obj = new JSONParser();
JSONArray array_obj = (JSONArray) parser_obj.parse("String from web service"); 
// in your case it will be "result" 

Then you can process it as per your need.

Sign up to request clarification or add additional context in comments.

3 Comments

You was right when said about incorrect format. The format was changed and was checked for validation. Now, it works without json-simple. Thank you =)
Glad that it is solved. Please accept the answer and upvote it.
@gowtham: Please add a question & paste the link here. I would surely try to help.
2

In my case I was not decoding the jSon string before parsing it as jSon object. The following worked for me.

JSONObject responseJSonObj = new JSONObject( URLDecoder.decode( result, "UTF-8" ) );

Where result contains the jSon string to be parsed.

Comments

1

JSON data should always be encoded in UTF-8 (and your data most likely is). However, you read it using the ISO-8859-1. Since your JSON data contains Cyrillic characters, they will lead to invalid data that can no longer be parsed as JSON. (In UTF-8, Cyrillic characters required two bytes. However, ISO-8859-1 treats each byte as a separate character.)

The fix is to use the correct encoding, most likely UTF-8:

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

Update:

The code you're using is posted all over the Internet, sometimes with ISO-8859-1 and sometimes with UTF-8. If you stick to the standards, JSON with ISO-8859-1 encoding is invalid.

The Android JSON parser is very unfortunate because it only supports strings as a parsing source. As a result, the complex code you're using is required to parse a JSON HTTP response. Memory and processing wise, it's pretty inefficient. It would be nice if Google would extend the JSON parser to directly work on an InputStream instance without taking the detour via a huge String instance.

Update 2:

I just realized that Android (starting with API level 11) contains a JSON parser working on InputStream. However, it's in a different package and only produces a stream of tokens, not JSONObject or JSONArray instances. I guess I'll write the missing code myself to come up with an easy to use and efficient JSON parser (producing JSONObject or JSONArray instances).

Update 3:

If the JSON text to parse is invalid, Android throw an exception containing the message:

Value [{ "Id": "5207fc6473516724343ce7a5", "Name": "Эриван", ... }] of type java.lang.String cannot be converted to JSONArray

Since there is not JSON data between the word Value and of in your message, I suspect that your JSON data is in fact empty.

In your code, you should first check the status code of the HTTP response (getStatusLine().getStatusCode()). Furthmore, I seems strange that you use a POST request without posting any data. Shouldn't you use a GET request?

2 Comments

Thank you for explaining. I did it as you said already. I've just forgot to change sample of code, but it isn't a solution of my problem.
@whisperofblood: See my update. I suspect that your JSON data is empty.
0

Your Json response seems just fine. However its not always guaranteed that the response string is always filled up with data. For that, I would suggest you to handle your array as below:

JSONArray jsonArr = null;

String jsonObjRecv = JSONGet.getJSONfromURL(URL_LIST);
if(!TextUtils.isEmpty(jsonObjRecv)){
    jsonArr = new JSONArray(jsonObjRecv);
}
else{
    Log.w("json", "jsonObjRecv is null");
}

1 Comment

instead of customizing your own exception message, i would suggest you to use e.printStackTrace(); and paste the entire exception stack in your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.