Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Parsing Json with special characters (utf-8)

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?

like image 450
grc Avatar asked Oct 23 '25 15:10

grc


1 Answers

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));
like image 117
Omatt Avatar answered Oct 25 '25 05:10

Omatt