I am trying to parse a JSONArray but unable to do so. I am getting Null as reply
MY JSONArray:
["{\"mapurl\":\"http:\\\/\\\/maps.google.com\\\/maps?q=17.XXXXXXXX,78.xxxxxxx\",\"caller\":\"+91xxxxxxxxx\",\"id\":1,\"reciever\":\"+91xxxxxxxx\",\"timpestamp\":\"3\"}","{\"mapurl\":\"http:\\\/\\\/maps.google.com\\\/maps?q=17.xxxxxxx,78.xxxxxxx\",\"caller\":\"+91xxxxxxxxxx\",\"id\":2,\"reciever\":\"+91xxxxxxxxxx\",\"timpestamp\":\"3\"}"]
I am passing this JSONArray from Android as a GET request in the parameter "add"
my PHP CODE:
<?php
if (isset($_GET['add'])) {
$jsonData = $_GET['add'];
$phpArray = json_decode($jsonData);
var_dump($phpArray);
}
else{
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
3 Answers 3
Looks as if your PHP configuration still has the deprecated magic_quotes feature enabled. Either disable magic_quotes in your PHP configuration or try to remove the extra backslashes added by the magic_quotes feature with the stripslashes()
function:
$jsonData = stripslashes($_GET['add']);
Comments
I experimented with your json. It's actually valid. I think it's because you're using $_GET
to pass the data. I suggest you use post
to send the Json data. However, if you must use $_GET
to send the data, make sure you JSON.stringify()
it. But if your data will be longer than what you have here, you might have a truncated url which of course, is the data.
That way your current code is very valid, including your json.
Comments
What you have here is actually several json-encoded objects stored as strings in a json array. Something funky going on with your encoder...
You can just loop through the array and decode each part:
$phpArray = array();
foreach(json_decode($_GET['add']) as $part) {
$phpArray[] = json_decode($part, true);
}
But you should fix it at the source really!
Unsure why you're getting NULL though. You should at least get an array of strings back using your code. I tested myself and did...
echo $_GET['add'];
at the top of your code?if ($phpArray == null) echo json_last_error_msg();
to see the error.[\"{\\\"mapurl\\\":\\\"http:\\\\\\/\\\\\\/maps.google.com\\\\\\/maps?q=17.xxxxx,78.xxxxxx\\\",\\\"caller\\\":\\\"+91XXXXXXX\\\",\\\"id\\\":1,\\\"reciever\\\":\\\"+91XXXXXXX\\\",\\\"timpestamp\\\":\\\"3\\\"}\",\"{\\\"mapurl\\\":\\\"http:\\\\\\/\\\\\\/maps.google.com\\\\\\/maps?q=17.xxxxxx,78.xxxxxx\\\",\\\"caller\\\":\\\"+91xxxxxxxx\\\",\\\"id\\\":2,\\\"reciever\\\":\\\"+91xxxxxxxx\\\",\\\"timpestamp\\\":\\\"3\\\"}\"]NULL
this is the response that i am getting