user2574427
user2574427

Reputation: 51

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

So I get that error when I try to parse the JSON Object. I have google the problem and I am still confused and can't find a solution to it. It looks like my code is correct.

This is the Android Java file

InputStream is = null;
String result = "";
protected String doInBackground(String... params) {
    try {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(params[0]);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();


        is = entity.getContent();
        Log.v("mysql", "Success");
    } catch (Exception e) {
        Log.v("log_tag", "Error in http connection " + e.toString());
    }
    return null;
}

protected void onPostExecute(String result) {
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
        }
        is.close();

        result=sb.toString();
        Log.v("result", result);
}catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
}

    try{
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                Log.i("log_tag","uID: "+json_data.getInt("uID")+
                        ", uName: "+json_data.getString("uName")+
                        ", uPass: "+json_data.getString("uPass")
                );
        }
}catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());

    }

}

The code for PHP file is this

    <?php
$username = "removed";
$password = "removed";
$database = "removed";
$user = "art";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die ("it's dead jim");

$q = mysql_query("SELECT * FROM user WHERE uName = '$user'");
while($e=mysql_fetch_assoc($q)){
        print(json_encode($e));
        $output[]=$e;
}

?>

The JSON value I receive is

{"uID":"1","uName":"art","uPass":"password"}

When I try to parse it I get:

Error parsing data org.json.JSONException: Value {"uID":"1","uName":"art","uPass":"password"} of type org.json.JSONObject cannot be converted to JSONArray

Upvotes: 1

Views: 11343

Answers (1)

Sushil
Sushil

Reputation: 8488

You data in the file is in JSONObject format and you are tryong to receive it in JSONArray format which is causing the problem. The line below is the culprit:

JSONArray jArray = new JSONArray(result);

Rather, you need to do something like this:

JSONObject jObject = null;
jObject = new JSONObject(mJsonString);
JSONArray jsonImageArray = jObject.getJSONArray("imageTarget");

Hope it helps.

Upvotes: 2

Related Questions