2

JSON response String containing an apostrophe

This is the key and value coming from the server.

"name": "men’s basketball wear with free product",

When I'm converting this JSON into pojo response Future<Product> returning me this when I print the string in the log.

PRODUCT NAME menâs basketball wear with free product

enter image description here

I have tried this solution but nothing is happening

replaceAll("'", "\'").replaceAll('"', "\'") 
replaceAll('"', '\\"')

I have tried in response class

Product.fromJsonMap(Map<String, dynamic> map):
        pid = map["pid"],
        aid = map["aid"],
        name = map["name"].replaceAll("'", "\'");

My HTTP request

http.Response res = await http.get(url);
Farhana Naaz Ansari
  • 7,524
  • 26
  • 65
  • 105
  • I guess you get this JSON from an HTTP request and it's an encoding issue. Check the content-type header of the response. – Günter Zöchbauer Mar 15 '19 at 05:21
  • @GünterZöchbauer this is coming from get service ` http.Response res = await http.get(url);` should I need to change at server side? – Farhana Naaz Ansari Mar 15 '19 at 05:28
  • 1
    Try with `"application/json; charset=utf-8"` and check what the content-type header of the response is – Günter Zöchbauer Mar 15 '19 at 05:37
  • @GünterZöchbauer still returning the same thing. – Farhana Naaz Ansari Mar 15 '19 at 05:38
  • 2
    You could first check the response headers as mentioned before – Günter Zöchbauer Mar 15 '19 at 05:44
  • @GünterZöchbauer Thanks I was not able to check and change response header, I will have to manage what I have and found the solution by Richard Heap answer. – Farhana Naaz Ansari Mar 15 '19 at 06:57
  • 2
    As you figured out, setting a `content-type` on the *request* isn't going to make any difference. As is typical with a `GET` you aren't actually sending any content *to* the server. You want the server to send its content back to you in UTF-8; in fact it already is - so there's nothing more you can do in the request to influence the response. The problem is that the server is forgetting to include the charset suffix with its `content-type`. Dart has a slightly unusual (for this day and age) default of LATIN-1 if the suffix is omitted. Glad you fixed it. – Richard Heap Mar 15 '19 at 13:22

2 Answers2

10

As @Richard Heap answer

  http.Response response = await http.get('SOME URL',headers: {'Content- Type':'application/json'});
    List<dynamic> responseJson = json.decode(utf8.decode(response.bodyBytes));
Farhana Naaz Ansari
  • 7,524
  • 26
  • 65
  • 105
  • This solution worked for me, thanks. Btw, no need for `Content-Type` header, just for consistency maybe you want `Accept` header with `application/json;charset=utf-8` value. – tudorprodan Dec 14 '20 at 13:00
0

Simply using utf8.decode() solves the issue for me.

Koofng
  • 137
  • 1
  • 4