Flutter-删除飞镖中的转义序列 [英] Flutter - Remove escape sequence in dart
问题描述
要将API响应字符串解码为JSON,json.decode()
可以正常工作.
这将解析类似于
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()
无法正常工作.
在Java中,我将StringEscapeUtils.unescapeJson()
用于相同的问题.
我搜索了Dart,但找不到如何对字符串中的字符进行转义.
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.
修改:
假设键数据的值为abc"de
因此,其对应的JSON为{"data":"abc\"de"}
因此,在序列化期间,此json字符串将转义以给出{\"data\":\"abc\\\"de\"}
作为响应,该响应由API发送.
因此,我的意图是删除转义序列,以便获得字符串{"data":"abc\"de"}
,稍后将使用json.decode()
对其进行解码.删除转义序列是使用Java中的StringEscapeUtils.unescapeJson()
完成的.
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.
推荐答案
json.decode
也可以解码单个字符串,因此您应该可以调用它两次.第一次它将返回一个字符串(转义字符已在其中解码),第二次它将返回该字符串到映射中:
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
}
这篇关于Flutter-删除飞镖中的转义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!