按 json 在字符串中使用换行符

Use newline in string by json

我有一个 JSON 这样的:

{
"luid": 1,
"uid": 1,
"description": "Inside there are some buildings:\n- houses,\n- skyscrapers,\n- bridges",
"visible": 1
}

当我在 dart 中获取 json 时,我将所有字段放在单独的 getter 中。

在 UI 中,在 Text 中打印描述字段,我看到:

Inside there are some buildings:\n- houses,\n- skyscrapers,\n- bridges

而不是:

Inside there are some buildings:
- houses,
- skyscrapers,
- bridges

代码是这样的:

_respserver =
        await cl.get('datacontents.json');
_analyzed = json.decode(utf8.decode(_respserver.bodyBytes));

Text(_analyzed['description'])

如何修复?

您可以修改收到的 JSON 字符串,将所有 \n 替换为真正的换行符。

根据您当前的输出,您有原始的单独 \n 字符彼此相邻。所以要解决这个问题,我们只需要找到所有这些实例并将它们替换为我们想要的。

我们首先要搜索 \\n 的实例,这可能看起来很复杂,但是一旦你考虑转义字符,它就会变成原始的 \n,这就是你当前真正的内容json。当 json 解码器看到这个时,它看不到换行符,因为你在开头用反斜杠转义它,导致输出中的文字 \n

一旦我们发现不受欢迎的实例,我们需要将其替换为我们真正想要的,\n。如前所述,这变成了原始 \n 。 json 解码器然后将其视为换行符并在解码输出中创建它,当您在 Text 小部件中显示它时会得到您想要的结果。

_respserver = await cl.get('datacontents.json');
String jsonRaw = utf8.decode(_respserver.bodyBytes);
jsonRaw = jsonRaw.replaceAll("\\n","\n");//Find and replace undesirable instances here
_analyzed = json.decode(jsonRaw);

Text(_analyzed['description'])

要在解码后执行,请执行以下操作:

_respserver = await cl.get('datacontents.json');
_analyzed = json.decode(utf8.decode(_respserver.bodyBytes));

_analyzed['description'] = _analyzed['description'].replaceAll("\n" ,"\n");

Text(_analyzed['description'])