I've been looking around the web for a way to send JSON to my server and I found this really helpful answer. I used that to send JSON to my server and the plan was then to decode it, however for some reason I can't seem to be able to get it right.
I use GSON to encode a HashMap
into a JSON string
Map<String, String> myData = new HashMap<String, String>();
myData.put("count", "1");
myData.put("id", "1000");
myData.put("name", "Äpple");
String json = new GsonBuilder().create().toJson(myData, Map.class);
With the JSON string I send it to my server using HttpPost
.
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
Brilliant, now I only have to receive the encoded JSON on my WAMP server and use the awesome builtin JSON functionality of php to decode it.
$json = file_get_contents('php://input');
for ($i = 0; $i <= 31; ++$i) {
$json = str_replace(chr($i), "", $json);
}
$json = str_replace(chr(127), "", $json);
if (0 === strpos(bin2hex($json), 'efbbbf')) {
$json = substr($json, 3);
}
$json = stripslashes($json);
$data = json_decode($json, true);
As it turns out the builtin JSON support perhaps isn't so awesome after all. Maybe it has something to do with the PHP version I am using (5.5.12
)?
Here is the JSON data I am trying so desperately to decode with php:
{"count":"1","id":"1000","name":"Äpple"}
If that isn't enough here is the hex dump of the $json
variable (after removing the "hidden characters" in my string):
7b22636f756e74223a2231222c226964223a2231303030222c226e616d65223a22c470706c65227d
The examples gives me "Malformed UTF-8 characters, possibly incorrectly encoded" from json_last_error()
.
Will someone be so kind to explain why and how I send properly encoded UTF-8 characters?