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

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?

This question is related to android json parsing

The answer is


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}")

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.


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);

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);
        }

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.


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.


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


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.


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);

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;

}

This worked for me

json = json.replace("\\\"","'");
JSONObject jo = new JSONObject(json.substring(1,json.length()-1));

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.


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"))

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.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?