8

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.

Abhishek Aggarwal
  • 207
  • 2
  • 4
  • 13
  • What encoding are you using for the quotation marks? If I try to replicate your error, I have problems even with the first string. But if I use normal quotation marks " then both string work correctly. – chemamolins Oct 12 '18 at 13:43
  • Please check the example I added in the edit part of the question. Also, no special quotation marks are used, just the normal double quotes. – Abhishek Aggarwal Oct 13 '18 at 06:30
  • Maybe you should try to serialize and then scape, or the contrary to what you do. I mean that the normal quotes should not be scaped. I tell you this because if I feed `{"data":"abc\\\"de"}` to `json.decode()` it works ok. So only the quote in the middle should be scaped. – chemamolins Oct 13 '18 at 08:56
  • I can't make changes in the API, as it is live for the android project. However, doing json.decode twice does work. – Abhishek Aggarwal Oct 15 '18 at 07:28

1 Answers1

9

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
}
Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275
  • How can I put a string in triple quotes ''' ''', if I received the string from an API? – João Abrantes Oct 21 '21 at 12:59
  • @JoãoAbrantes it's hard to answer without understanding what you're trying to do. You can't/shouldn't need to use triple quotes. The triple quotes just affect how the literal string is parsed in the Dart source file. If your string is a variable populated at runtime, it's not appearing literally in the source code so there's nowhere to have triple quotes. – Danny Tuppeny Nov 03 '21 at 21:29