74

I have a JSON file with 2 JSON-Arrays in it: One Array for routes and one Array for sights.

A route should consist of several sights where the user gets navigated to. Unfortunately I am getting the error:

JSONException: Value of type java.lang.String cannot be converted to JSONObject

Here are my variables and the code that parses the JSON-File:

private InputStream is = null;
private String json = "";
private JSONObject jObj = null;

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    // hier habe ich das JSON-File als String
    json = sb.toString();
    Log.i("JSON Parser", json);
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;
}

Log.i("JSON Parser", json); shows me that at the beginning of the generated string there is a strange sign: enter image description here

but the error happens here:

try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

04-22 14:01:05.043: E/JSON Parser(5868): Error parsing data org.json.JSONException: Value //STRANGE SIGN HERE // of type java.lang.String cannot be converted to JSONObject

anybody has a clue on how to get rid of these signs in order to create the JSONObject?

sam
  • 2,780
  • 1
  • 17
  • 30
RCK69
  • 909
  • 4
  • 12
  • 20

15 Answers15

51

Reason is some un-wanted characters was added when you compose the String. The temp solution is

return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));

But try to remove hidden characters on source String.

Khai Nguyen
  • 3,065
  • 1
  • 31
  • 24
43

see this http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-

JSONObject

public JSONObject(java.lang.String source)
           throws JSONException

Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.

Parameters:
    source - `A string beginning with { (left brace) and ending with } (right brace).` 
Throws:
    JSONException - If there is a syntax error in the source string or a duplicated key.

you try to use some thing like:

new JSONObject("{your string}")
Shog9
  • 156,901
  • 35
  • 231
  • 235
Zaz Gmy
  • 4,236
  • 3
  • 19
  • 30
  • thx, my JSON-File starts with the left brace { and ends with the right brace }. I used this JSON-validator to ensure that the JSON-Syntax is correct. Problem is, that the string I am generating out of the JSON has a strange sign in front of as yo can see here: http://i.stack.imgur.com/uOiX8.png – RCK69 Apr 22 '12 at 12:44
  • I have he same problem, in some case of "success" my app cashes because of same error of this question. but in another "success" mode it's work correctly. the point is if in mostly case it works, so I confused. – Mahdi Apr 29 '14 at 08:17
21

Had the same problem for few days. Found a solution at last. The PHP server returned some unseen characters which you could not see in the LOG or in System.out.

So the solution was that i tried to substring my json String one by one and when i came to substring(3) the error went away.

BTW. i used UTF-8 encoding on both sides. PHP side: header('Content-type=application/json; charset=utf-8');

JAVA side: BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);

So try the solution one by one 1,2,3,4...! Hope it helps you guys!

try {
            jObj = new JSONObject(json.substring(3));
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
        }
MTurPash
  • 979
  • 1
  • 11
  • 18
  • I love your solution :) I encountered the same problem, and I fixed it with your solution. No matter how I changed the charset of the document, there are still some invisible character in it. Thanks for your solution:) – code4j Nov 13 '12 at 22:41
  • 4
    I have the same problem but cannot see how making a substring would make this go away? – EHarpham Nov 14 '12 at 23:03
  • To decide the value to use in substring, just run your app in debug mode and copy the value use in JSONObject. Paste it in to Notepad++ and you'll see the character which fails your JSON. No need to try several times. – saji159 Jul 18 '13 at 12:01
  • i found my problem. there was some unwanted echo on php :( but i uped your answer cause it's wisefull ;) – Mahdi Apr 29 '14 at 08:32
11

This worked for me

json = json.replace("\\\"","'");
JSONObject jo = new JSONObject(json.substring(1,json.length()-1));
Alex Escobar
  • 141
  • 1
  • 4
9

Here is UTF-8 version, with several exception handling:

static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
static HttpResponse httpResponse = null;

public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUseExpectContinue(params, true);
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        HttpGet httpPost = new HttpGet( url);
        httpResponse = httpClient.execute( httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           
    } catch (UnsupportedEncodingException ee) {
        Log.i("UnsupportedEncodingException...", is.toString());
    } catch (ClientProtocolException e) {
        Log.i("ClientProtocolException...", is.toString());
    } catch (IOException e) {
        Log.i("IOException...", is.toString());
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8); //old charset iso-8859-1
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        reader.close();
        json = sb.toString();
        Log.i("StringBuilder...", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (Exception e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        try {
            jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
        } catch (Exception e0) {
            Log.e("JSON Parser0", "Error parsing data [" + e0.getMessage()+"] "+json);
            Log.e("JSON Parser0", "Error parsing data " + e0.toString());
            try {
                jObj = new JSONObject(json.substring(1));
            } catch (Exception e1) {
                Log.e("JSON Parser1", "Error parsing data [" + e1.getMessage()+"] "+json);
                Log.e("JSON Parser1", "Error parsing data " + e1.toString());
                try {
                    jObj = new JSONObject(json.substring(2));
                } catch (Exception e2) {
                    Log.e("JSON Parser2", "Error parsing data [" + e2.getMessage()+"] "+json);
                    Log.e("JSON Parser2", "Error parsing data " + e2.toString());
                    try {
                        jObj = new JSONObject(json.substring(3));
                    } catch (Exception e3) {
                        Log.e("JSON Parser3", "Error parsing data [" + e3.getMessage()+"] "+json);
                        Log.e("JSON Parser3", "Error parsing data " + e3.toString());
                    }
                }
            }
        }
    }

    // return JSON String
    return jObj;

}
izbrannick
  • 349
  • 4
  • 12
7

This is simple way (thanks Gson)

JsonParser parser = new JsonParser();
String retVal = parser.parse(param).getAsString();

https://gist.github.com/MustafaFerhan/25906d2be6ca109f61ce#file-evaluatejavascript-string-problem

Mustafa Ferhan
  • 240
  • 2
  • 4
5

I think the problem may be in the charset that you are trying to use. It is probably best to use UTF-8 instead of iso-8859-1.

Also open whatever file is being used for your InputStream and make sure no special characters were accidentally inserted. Sometimes you have to specifically tell your editor to display hidden / special characters.

Nic Raboy
  • 3,143
  • 24
  • 26
4
return response;

After that get the response we need to parse this By:

JSONObject myObj=new JSONObject(response);

On response there is no need for double quotes.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
3

I made this change and now it works for me.

//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
Jamal
  • 726
  • 5
  • 5
2

The 3 characters at the beginning of your json string correspond to Byte Order Mask (BOM), which is a sequence of Bytes to identify the file as UTF8 file.

Be sure that the file which sends the json is encoded with utf8 (no bom) encoding.

(I had the same issue, with TextWrangler editor. Use save as - utf8 (no bom) to force the right encoding.)

Hope it helps.

stevenwood
  • 211
  • 1
  • 6
2

In my case the problem occured from php file. It gave unwanted characters.That is why a json parsing problem occured.

Then I paste my php code in Notepad++ and select Encode in utf-8 without BOM from Encoding tab and running this code-

My problem gone away.

Rasel
  • 5,488
  • 3
  • 30
  • 39
  • I did the same as you mentioned but still getting the same error: `org.json.JSONException: Value Server of type java.lang.String cannot be converted to JSONObject`. How can I find if my php file returns a warning? Actually it returns correct `JSON` without incorrect or hidden characters. – blueware Oct 24 '18 at 22:27
  • @blueware before json_encode you can see your data printing it using print_r() .Characters with black ? marked are the culprit. remove those from your data then encoding will work – Rasel Oct 25 '18 at 03:55
2

In my case, my Android app uses Volley to make a POST call with an empty body to an API application hosted on Microsoft Azure.

The error was:

JSONException: Value <p>iisnode of type java.lang.String cannot be converted to JSONObject

This is a snippet on how I was constructing the Volley JSON request:

final JSONObject emptyJsonObject = new JSONObject();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, emptyJsonObject, listener, errorListener);

I solved my problem by creating the JSONObject with an empty JSON object as follows:

final JSONObject emptyJsonObject = new JSONObject("{}");

My solution is along the lines to this older answer.

Community
  • 1
  • 1
  • I just change the method from `GET` to `POST` and send an empty object like what you did and it worked from me. Thanks – blueware Oct 25 '18 at 07:57
1

if value of the Key is coming as String and you want to convert it to JSONObject,

First take your key.value into a String variable like

 String data = yourResponse.yourKey;

then convert into JSONArray

JSONObject myObj=new JSONObject(data);
Sachin Rajput
  • 4,326
  • 2
  • 18
  • 29
1

For me, I just needed to use getString() vs. getJSONObject() (the latter threw that error):

JSONObject jsonObject = new JSONObject(jsonString);
String valueIWanted = jsonObject.getString("access_token"))
codingjeremy
  • 5,215
  • 1
  • 36
  • 39
0

if you are using expo cli run this command will fix it

expo r -c 
Zoro ا
  • 11
  • 1