6

I have a json array like this:

[
{
"variable1":"example",
"variable2": "example1\nexample2\nexample3"
},
{
"variable1":"exampleLast\n",
"variable2": "example1\nexample2\nexample3"
}
]

I am trying to parse this json a List in Flutter.

List posts = json.decode(response.data);

When I tried using 'dart:convert' it gives error FormatException... Control character in string (at line...).

I found this issue on Github but I can not find solution.
https://github.com/dart-lang/convert/issues/10

Jannie Theunissen
  • 28,256
  • 21
  • 100
  • 127
Enis Erkaya
  • 71
  • 2
  • 6

4 Answers4

4

You just need to replace single slash to double slash and everything goes fine.

String replaced = string.replaceAll(r'\', r'\\');

Arjun Vyas
  • 409
  • 5
  • 14
2

Just replace the single backslash(\n) with double backslash(\\n) in your code:

[{
    "variable1": "example",
    "variable2": "example1\\nexample2\\nexample3"
},
{
    "variable1": "exampleLast\\n",
    "variable2": "example1\\nexample2\\nexample3"
}]

You need to escape the \ in your string (turning it into a double-), otherwise it will become a newline in the JSON source, not the JSON data.

Arbaz Alam
  • 1,172
  • 1
  • 14
  • 24
2

Previous answers didn't help me. In the mentioned Github thread there is a good solution: add r to make compiler think that there is no special characters in the line.

final jsonContent = r'''{ "pageNumber": 0, "pageCount": 0, "transactionId": "126cf723-1d57-4f49-8fb2-072b7c23ec1e", "entries": [ { "content": "{\"resourceType\":\"Bundle\",\"id\":\"DRiefcase_2021-03-15__ManjoorKapoor_Pres-13116\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2021-01-20T04:51:59.1497479Z\",\"profile\":[\"https:\\/\\/nrces.in\\/ndhm\\/fhir\\/r4\\/StructureDefinition\\/DocumentBundle\"]}}}]}''';
Valentina Konyukhova
  • 4,464
  • 2
  • 24
  • 33
1

And you can replace it like this

String replaced = string.replaceAll('\n', '\\n');

also check this response

ramzieus
  • 138
  • 11