EHarpham
EHarpham

Reputation: 622

PHP SQL array json encode error when converting to java

I am echoing a json set of results back to android:

$result = mysql_query($query) or die(mysql_error());
    $resultNo = mysql_num_rows($result);

    // check for successful store
    if ($result != null) {

        $rows = array();
        while($r = mysql_fetch_assoc($result)) {
        $rows[] = $r;
}   
return json_encode($rows);

    } else {
        return false;
    }
}

But when I try to convert the string to a JSONObject at the other end i get:

11-13 22:18:41.990: E/JSON(5330): "[{\"email\":\"fish\"}]"

11-13 22:18:41.990: E/JSON Parser(5330): Error parsing data org.json.JSONException: Value [{"email":"fish"}] of type java.lang.String cannot be converted to JSONObject

I have tried this with a larger result set and thought that it would be something to do with null values however trying it as above with just one value still returns an error.

Any help greatly appreciated

EDIT:

Android methods...

public JSONObject searchPeople(String tower) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", search_tag));
    params.add(new BasicNameValuePair("tower", tower));

    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    return json;
}

JSON Parser class...

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    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();
        json = sb.toString();
        Log.e("JSON", 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;

}

Upvotes: 0

Views: 1281

Answers (5)

Nevuroth
Nevuroth

Reputation: 126

You need to escape certain characters added by PHP, as well as substring your json string to cut out the additional characters at the front of the returned string.

One way to do it is like so:

ANDROID/JAVA code

JSONObject response = new JSONObject(responseString.substring(responseString.indexOf('{'),responseString.indexOf('}') +1).replace("\\",""));

You should do it a bit more neatly, but the point is that you have to ensure that the string you're passing in has no hidden characters, and to replace the first """ character with nothing as it can cause the exception.

Upvotes: 0

jnthnjns
jnthnjns

Reputation: 8925

As @MikeBrant mentioned above, you need to pass through JSONArray first.

Replace this:

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

With this:

// try parse the string to a JSON object
try {
    JSONArray jArray = new JSONArray(json);        

    for(i=0; i < jArray.length(); i++) {
        JSONObject jObj = jArray.getJSONObject(i);
        Log.i("jObj", "" + jObj.toString());

        // Parsing example
        String email = jObj.getString("email");
        Log.i("email", email);
    }

} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

PHP w/ str_replace:

$result = mysql_query($query) or die(mysql_error());
    $resultNo = mysql_num_rows($result);

    // check for successful store
    if ($result != null) {

        $rows = array();
        while($r = mysql_fetch_assoc($result)) {
        $rows[] = $r;
}

$json_string = json_encode($rows);
$json_string = str_replace("\\", "", $json_string, $i);
return $json_string;

    } else {
        return false;
    }
}

Upvotes: 1

Zdenek Machek
Zdenek Machek

Reputation: 1744

I had similar problem when I needed to pass json data from php to java app, this solved my problem:

$serialliazedParams = addslashes(json_encode($parameters));

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71414

What you are passing to JSONObject is in fact an array with a single object in it.

JSONObjectis expecting the syntax to be only representative of a single object containing key-value pairs (i.e. properties).

You need to not pass an array for this to work, or you need to use JSONArray to decode the JSON.

Upvotes: 0

conners
conners

Reputation: 1420

    $result = mysql_query($query) or die(mysql_error());
    $resultNo = mysql_num_rows($result);

    // check for successful store
    if ($result != null) {

        $rows = array();
        while($r = mysql_fetch_assoc($result)) {
            $rows[] = $r;
        }   
        return json_encode($rows);

    } else {
        return false;
    }

I think it's just your braces

Upvotes: 0

Related Questions