I’m just a simple guy working my way through passing JSON from Android, and I’ve come across a strange problem.
To better understand how JSON works between PHP and Android, I started by created a Json (OK) passing it to PHP and echoing the exact same file back – just to see what happens.
The problem is that the outgoing JSON.toString() is as follows:
{“Age at Death “:32.5,”Enemy”:”Darius”,”Battles”:[“Issus”,”Arbela”],”Death”:-323}
But the returning JSON.toString() is:
{\”Age at Death \”:32.5,\”Enemy\”:\”Darius\”,\”Battles\”:[\”Issus\”,\”Arbela\”],\”Death\”:-323}
This throws an error when I try to read the Json from PHP. (PS: this is one problem I’ve identified; maybe the source is elsewhere, so don’t let me set you on the wrong track)
Here is my code:
Android:
private void connectToURL() throws UnsupportedEncodingException {
// TODO Auto-generated method stub
HttpParams httpParams = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParams);
String url = "http://www.this.url.is.correct.php";
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
String hello = myJson.toString();
nameValuePair.add(new BasicNameValuePair("Json", myJson.toString()));
HttpPost request = new HttpPost(url);
request.setEntity(new UrlEncodedFormEntity(nameValuePair));
//ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String myResponse = EntityUtils.toString(entity);
showResponse(myResponse);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void showResponse(String thisResponse) {
try {
JSONObject newJson = new JSONObject(thisResponse);
viewer02.setText(newJson.toString(2));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and here is the PHP (it doesn’t get simpler than this):
<?php
$obj = $_POST['Json'];
//$json = json_encode($obj);
//$string = $json->{'enemy'};
echo $obj;
?>
That happens because of magic quotes options turned on in php.
IIRC it’s currently deprecated and actually isn’t recommended to use (because of it makes no sense)