通过 json 在字符串中使用换行符

dam*_*034 4 newline dart flutter

我有一个像这样的 JSON:

{
"luid": 1,
"uid": 1,
"description": "Inside there are some buildings:\n- houses,\n- skyscrapers,\n- bridges",
"visible": 1
}
Run Code Online (Sandbox Code Playgroud)

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

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

Inside there are some buildings:\n- houses,\n- skyscrapers,\n- bridges
Run Code Online (Sandbox Code Playgroud)

代替:

Inside there are some buildings:
- houses,
- skyscrapers,
- bridges
Run Code Online (Sandbox Code Playgroud)

代码是这样的:

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

Text(_analyzed['description'])
Run Code Online (Sandbox Code Playgroud)

怎样才能修好呢?

Chr*_*ore 5

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

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

我们首先必须搜索 的实例\\\\n,这可能看起来很复杂,但是一旦考虑转义字符,它就会变成 raw \\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'])
Run Code Online (Sandbox Code Playgroud)

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

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

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

Text(_analyzed['description'])
Run Code Online (Sandbox Code Playgroud)