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;

}
EHarpham
  • 602
  • 1
  • 17
  • 34
  • first http://kb.mozillazine.org/JavaScript_is_not_Java secondly, give me a sec – conners Nov 13 '12 at 22:35
  • [This](http://stackoverflow.com/a/3563464/1134705) may help you – jnthnjns Nov 13 '12 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 – EHarpham Nov 13 '12 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` – jnthnjns Nov 13 '12 at 23:11
  • Yes at the other end is in android. Code posted in edit. – EHarpham Nov 13 '12 at 23:16
  • @EHarpham See my answer below, Let me know if that helps – jnthnjns Nov 13 '12 at 23:47

5 Answers5

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;
    }
}
jnthnjns
  • 8,962
  • 4
  • 42
  • 65
  • 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 – EHarpham Nov 14 '12 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. – jnthnjns Nov 14 '12 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 – EHarpham Nov 14 '12 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 http://jsonlint.com/ – jnthnjns Nov 14 '12 at 20:38
  • Thanks for that link. Ok so I am returning valid JSON but still unable to parse the string to a json array??? Must be something wrong with my JSON Parser class but i cant see why as it parsed JSON from a single object fine – EHarpham Nov 14 '12 at 20:51
  • @EHarpham Hrm, that is interesting. I've compared my `JSON` with yours and if your Java matches mine above then we are doing it the same, except mine is through `AsyncTask`. Just for curiosity's sake, what if you change your Java back to what you had before, passing the result through a `JSONObject`, instead of an `JSONArray` – jnthnjns Nov 14 '12 at 21:22
  • 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??? – EHarpham Nov 14 '12 at 21:32
  • @EHarpham Good find, hope that helps. Not very reassuring to know that a PHP update or a change in web hosting may break my application in the future. – jnthnjns Nov 14 '12 at 21:48
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

conners
  • 1,420
  • 4
  • 18
  • 28
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.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • Hmm, Mike I thought similar at first glance, but... It should still be legal to do a key=>value array – conners Nov 13 '12 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 – conners Nov 13 '12 at 22:44
  • @conners NOt according to the documentation http://www.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. – Mike Brant Nov 13 '12 at 22:45
  • is there a way to do this without value pairs? – EHarpham Nov 13 '12 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. – Mike Brant Nov 13 '12 at 23:16
  • Hi Mike. I changed my code to convert the encoded string of results to JSONArray rather than JSONObject however got the same error that the string cannot be converted. – EHarpham Nov 13 '12 at 23:40
  • Does the actual String that you get in Java have the slashes before all the double-quotes? If so, you will need to remove them? – Mike Brant Nov 14 '12 at 00:45
  • Hi Mike. Now I have followed Asoks answer below and the slashes are visible in the string and then removed when it tries to convert to JSON but still receiving the error. Please see edit – EHarpham Nov 14 '12 at 18:39
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));
Zdenek Machek
  • 1,758
  • 1
  • 20
  • 30
  • 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]); – Zdenek Machek Nov 13 '12 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? – EHarpham Nov 13 '12 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.

Nevuroth
  • 126
  • 6