Search code examples
dartflutterunescapestring

Flutter - Remove escape sequence in dart


To decode API response string to JSON, json.decode() works fine.
This will parse a JSON string similar to

{ "Response" : {"Responsecode" : "1" , "Response" : "Success"}}

But in my case, the response comes in the serialized form like:

{\"Response\" : {\"Responsecode\" : \"0\" , \"Response\" : \"Success\"}}

json.decode() won’t work.

In Java, I used StringEscapeUtils.unescapeJson() for the same problem.
I searched for Dart but couldn’t find how to unescape characters in a string.

Edit:
Suppose, the value of key data is abc"de
So, its corresponding JSON would be {"data":"abc\"de"}
And hence during serialization, this json string is escaped to give {\"data\":\"abc\\\"de\"} as the response, which is sent by the API.
So, my intention is to remove the escape sequences, so that I can get the string {"data":"abc\"de"}, which would later be decoded using json.decode(). Removing the escape sequences was done using StringEscapeUtils.unescapeJson() in java.


Solution

  • json.decode can decode single strings too, so you should be able to just call it twice. The first time it'll return you a string (where the escape characters have been decoded) and the second time it'll decode that string into the map:

    import 'dart:convert';
    
    void main() {
      var a = r'''"{\"Response\" : {\"Responsecode\" : \"0\" , \"Response\" : \"Success\"}}"''';
      var b = json.decode(json.decode(a));
      print(b['Response']['Responsecode']); // 0
      print(b['Response']['Response']); // Success
    }