问题描述
{
"luid": 1,"uid": 1,"description": "Inside there are some buildings:\n- houses,\n- skyscrapers,\n- bridges","visible": 1
}
当我在dart中获取json时,我将所有字段放在单独的getter中。
在用户界面中,在Text
中打印说明字段,我看到:
Inside there are some buildings:\n- houses,\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'])