Reputation: 411
I have a JSON like this:
{
"luid": 1,
"uid": 1,
"description": "Inside there are some buildings:\n- houses,\n- skyscrapers,\n- bridges",
"visible": 1
}
When I fetch the json in dart, I put all the fields in separate getters.
In the UI, printing the description field in a Text
, I see:
Inside there are some buildings:\n- houses,\n- skyscrapers,\n- bridges
Instead of:
Inside there are some buildings:
- houses,
- skyscrapers,
- bridges
The code is this:
_respserver =
await cl.get('datacontents.json');
_analyzed = json.decode(utf8.decode(_respserver.bodyBytes));
Text(_analyzed['description'])
How can fix?
Upvotes: 4
Views: 4577
Reputation: 17133
You can modify your received JSON string to replace all of the \n
with a real newline character.
Based on your current output you have raw separate \
and n
characters next to each other. So to fix this we just need to find all of those instances and replace them with what we want.
We first have to search for instances of \\\\n
, which may seem complicated, but once you consider the escape characters, it turns into a raw \\n
, which is what's really currently in your json. When the json decoder sees this, it doesn't see a newline character since you escape it with the backslash at the beginning, leading to a literal \n
in the output.
Once we find the undesirable instances, we need to replace it with what we really want, \\n
. This turns into a raw \n
as explained before. The json decoder then see this as a newline character and creates it as such in the decoded output leading to your desired result when you show it in the Text
widget.
_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'])
To do it after decoding, do the following:
_respserver = await cl.get('datacontents.json');
_analyzed = json.decode(utf8.decode(_respserver.bodyBytes));
_analyzed['description'] = _analyzed['description'].replaceAll("\\n" ,"\n");
Text(_analyzed['description'])
Upvotes: 5