json으로 문자열에 줄 바꿈 사용

Aug 24 2020

다음과 같은 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'])

어떻게 고칠 수 있습니까?

답변

3 ChristopherMoore Aug 24 2020 at 22:30

수신 된 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'])