在 Dart 中将现有字符串转换为原始字符串

Vij*_*jay 4 json dart

从 HTTP 响应解码字符串时,我得到 FormatException。这是因为字符串中的 \n 字符。当我将字符串转换为原始字符串时,它会起作用。

声明一个原始字符串很容易

String raw = r'Hello \n World';
Run Code Online (Sandbox Code Playgroud)

但是如何将现有字符串转换为原始字符串?

String notRaw = 'Hello \n World';

String raw = r'${notRaw}';
Run Code Online (Sandbox Code Playgroud)

上面的语句不起作用,因为 r' 被视为原始字符串之后的所有内容。

我有两个问题

1) 如何在解码 JSON 时避免 \n 问题。2) 如何将现有的字符串变量转换为原始字符串。

import 'dart:convert';

void main() {

      var jsonRes = """
    {
            "response-list": {
                "response": [
                    {
                        "attribute": {
                            "@name": "Problem",
                            "@isEditable": false,
                            "@value": "Services fail to respond; for example:\n\n1) unable to connect.\n2) Slow response on the console.\n3)no response."
                        }
                    }
                ]
            }
        }
        """;
var jsonStr = json.decode(jsonRes);
print (jsonRes);
}
Run Code Online (Sandbox Code Playgroud)

转换为原始字符串

import 'dart:convert';

void main() {

      var jsonRes = r"""
    {
            "response-list": {
                "response": [
                    {
                        "attribute": {
                            "@name": "Problem",
                            "@isEditable": false,
                            "@value": "Services fail to respond; for example:\n\n1) unable to connect.\n2) Slow response on the console.\n3)no response."
                        }
                    }
                ]
            }
        }
        """;
var jsonStr = json.decode(jsonRes);
print (jsonRes);
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 6

没有转换为原始字符串这样的事情。原始字符串只是 Dart 语法结构,而不是字符串的属性。

代替

String notRaw = 'Hello \n World';
Run Code Online (Sandbox Code Playgroud)

用

String notRaw = 'Hello \\n World';
Run Code Online (Sandbox Code Playgroud)

获得与原始字符串语法相同的字符串表示形式。

r'xxx'意思xxx是字面意思。没有r \n将转换为实际的换行符。当反斜杠被转义时 '\\n',则将其解释为 raw '\n'。
因此,使用原始语法 ( r'xxx') 只是避免了每个\和$单独的转义。

另请参阅如何处理 JSON 中的换行符?


小智 5

尝试这个:

String string2Raw(String x) => '\r$x';
Run Code Online (Sandbox Code Playgroud)