0

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;

}
6
  • first kb.mozillazine.org/JavaScript_is_not_Java secondly, give me a sec Commented Nov 13, 2012 at 22:35
  • This may help you Commented Nov 13, 2012 at 22:48
  • Asok thanks this was the original way I was doing it but I was having trouble passing back arrays of rows. conners im not sure why you have posted that link I have not made any mention to JS in this post Commented Nov 13, 2012 at 22:51
  • @EHarpham When you say "at the other end", does this mean Android? If so, Can you show us your Android side as well as your output from return json_encode($rows);. First line in the error code tells me that you need to run stripslashes before json_encode Commented Nov 13, 2012 at 23:11
  • Yes at the other end is in android. Code posted in edit. Commented Nov 13, 2012 at 23:16

5 Answers 5

1

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;
    }
}
8
  • Thanks for your answer but I have tried your changes and am receiving the same JSON error that the string cannot be converted. The slashes now appear in the string however it is still not able to convert Commented Nov 14, 2012 at 18:37
  • @EHarpham Not a problem, let's try to walk through this. Is the stripslases() PHP function not working? There are other character replace functions that you could use. Just remember that the backslashes you're getting are escape characters so you'll need to escape them. For example: replaceAll("\\", ""); would replace one `` with nothing. Commented Nov 14, 2012 at 20:09
  • I have posted the json error i am currently getting in the edit. You are correct I have tested output with and without stripslashes and it is the same so stripslashes() is not working. addslashes() does work on the results however Commented Nov 14, 2012 at 20:30
  • @EHarpham I just edited the PHP portion of my answer above. I tested using your LogCat output and got a valid JSON return. FYI to validate JSON I use jsonlint.com Commented Nov 14, 2012 at 20:38
  • 1
    Tried that but still no luck. I suspect that it has something to do with hidden characters from PHP. Thttp://stackoverflow.com/questions/10267910/jsonexception-value-of-type-java-lang-string-cannot-be-converted-to-jsonobject third post down??? Commented Nov 14, 2012 at 21:32
0
    $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

0
0

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.

8
  • Hmm, Mike I thought similar at first glance, but... It should still be legal to do a key=>value array Commented Nov 13, 2012 at 22:42
  • oh crikey I am wrong it's an android issue, not PHP.. yes mike is right it's how you are de-serialising it it's not the same what you are squirting out isn't what you are sucking in Commented Nov 13, 2012 at 22:44
  • @conners NOt according to the documentation json.org/javadoc/org/json/JSONObject.html. JSONObject's external form is specifically mentioned to be a string wrapped in curly braces. And that the constructor converts this external form into the object. Commented Nov 13, 2012 at 22:45
  • is there a way to do this without value pairs? Commented Nov 13, 2012 at 23:07
  • Not sure I follow. If what you really intend to pass is an array representing rows of the database, simply use JSONArray instead of JSONObject and you should be good. The enclosing array can hold other objects or arrays in the value portion of the key-value pairs. Basically, you just need to pick the right class to use depending on what the outermost data structure in the JSON is that you want to work with. Commented Nov 13, 2012 at 23:16
0

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));
2
  • no, it's php array $serialliazedParams then is something passed to java app, in java: import net.sf.json.JSONObject; ... JSONObject jsonObject = JSONObject.fromObject(args[1]); Commented Nov 13, 2012 at 22:53
  • Thanks I have tried this but it appears to add more slashes. Which value should I be adding in my php code? Commented Nov 13, 2012 at 23:05
0

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.

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.