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

标签 json dart

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

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

String raw = r'Hello \n World';

但是如何将现有字符串转换为原始字符串?
String notRaw = 'Hello \n World';

String raw = r'${notRaw}';

上面的语句不起作用,因为一切都在 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);
}

转换为原始字符串
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);
}

最佳答案

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

代替

String notRaw = 'Hello \n World';


String notRaw = 'Hello \\n World';

获得与原始字符串语法相同的字符串表示形式。
r'xxx'意思是拿xxx字面上地。无 r \n将被转换为实际的换行符。当反斜杠被转义时,如 '\\n' ,那么这被解释为原始 '\n' .
因此,使用原始语法( r'xxx' )只是避免了每个 \ 的转义和 $个别。

另见 How do I handle newlines in JSON?

关于json - 在 Dart 中将现有字符串转换为原始字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55120264/

相关文章:

asynchronous - 在 Dart 中,如何确保流更新在继续之前完成?

python - 如何在 Json 对象前面添加 ""Users": "in Python?

java - 逗号导致不必要的字符串分割

javascript - pebbleJS 中的 json 数据提取

flutter - Gradle任务assembleDebug失败,退出代码为1,如何解决此问题?

asynchronous - 在 dart 的类中使用从 Future 返回的值

ios - 如何使用 SDWebImage 将图像从 JSON 加载到 UIImageView?

json - jackson 序列化有时会厌倦时区

dart - 如何从 Dart 中的 map 中过滤空值

flutter - 如何在两个小部件之间共享公共(public)参数?