Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;

}
share|improve this question
 
first kb.mozillazine.org/JavaScript_is_not_Java secondly, give me a sec –  conners Nov 13 '12 at 22:35
 
This may help you –  Asok 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 –  Asok 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
show 1 more comment

4 Answers

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;
    }
}
share|improve this answer
 
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. –  Asok 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 jsonlint.com –  Asok Nov 14 '12 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-la‌​ng-string-cannot-be-converted-to-jsonobject third post down??? –  EHarpham Nov 14 '12 at 21:32
show 3 more comments
    $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

share|improve this answer
 
the final brace is just part of a wider piece of code –  EHarpham Nov 13 '12 at 22:43
add comment

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.

share|improve this answer
 
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 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
show 3 more comments

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));
share|improve this answer
 
is $parameters here the json encoded results? –  EHarpham Nov 13 '12 at 22:49
 
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.