Reputation: 151
I get FormatException when decoding the string from an HTTP response. It's because of the \n character in the string. It works when I convert the string a raw string.
It's easy to declare a raw string
String raw = r'Hello \n World';
But how can I convert an existing string to a raw string?
String notRaw = 'Hello \n World';
String raw = r'${notRaw}';
the above statement doesn't work as everything is after r' is treated as raw String.
I'm having two questions
1) How to avoid the \n issue when decoding JSON. 2) How to convert an existing string variable to a raw string.
import 'dart:convert';
void main() {
var jsonRes = """
{
"response-list": {
"response": [
{
"attribute": {
"@name": "Problem",
"@isEditable": false,
"@value": "Services fail to respond; for example:\n\n1) unable to connect.\n2) Slow response on the console.\n3)no response."
}
}
]
}
}
""";
var jsonStr = json.decode(jsonRes);
print (jsonRes);
}
Converting to Raw String
import 'dart:convert';
void main() {
var jsonRes = r"""
{
"response-list": {
"response": [
{
"attribute": {
"@name": "Problem",
"@isEditable": false,
"@value": "Services fail to respond; for example:\n\n1) unable to connect.\n2) Slow response on the console.\n3)no response."
}
}
]
}
}
""";
var jsonStr = json.decode(jsonRes);
print (jsonRes);
}
Upvotes: 13
Views: 9144
Reputation: 1
You can do something like this:
String notRaw = 'Hello \n World';
String raw = notRaw.replaceAll('\n', r'\n');
Upvotes: 0
Reputation: 658263
There is no such thing as converting to a raw string. A raw string is just a Dart syntax construct, not a property of the string.
Instead of
String notRaw = 'Hello \n World';
use
String notRaw = 'Hello \\n World';
to get the same string representation that would get with the raw string syntax.
r'xxx'
means take xxx
literally. Without r
\n
will be converted to an actual newline character. When the backslash is escaped like '\\n'
, then this is interpreted as raw '\n'
.
So using raw syntax (r'xxx'
) just spares escaping every \
and $
individually.
See also How do I handle newlines in JSON?
Upvotes: 8