I have a pretty basic php code that generates a JSON file with some data:
$json = json_encode($theData, JSON_PRETTY_PRINT | JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
file_put_contents('api.json', $json);
When I parse it in my Flutter app, it returns special characters and not characters like "éóáêô".
I was parsing json file in Flutter like this:
var data = await http.get("xxxx/api.json", headers: {'Content-Type': 'application/json'});
if (data.statusCode == 200) {
print('Status Code 200: Ok!');
var jsonData = json.decode(data.body);
Then, I figure out that changing:
json.decode(data.body);
by:
json.decode(utf8.decode(data.bodyBytes));
Solved the problem!
Question is: Why using utf8.decode and bodyBytes solved the problem? Am I creating the JSON file with PHP properly?
You're able to fetch the http Response body by using either Response.body or Response.bodyBytes. The advantage of using bodyBytes is it fetches the bytes directly. Common uses for this is if you're expecting images to be displayed through parsing bytes. With body - this is commonly used if you're expecting plain Strings.
Since you're expecting special characters from the http response, it's best to fetch its bytes directly before using utf8.decode()
json.decode(utf8.decode(data.bodyBytes));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With