'Why FormatException when decode JSON from string value (i.e. only [A-Z][a-z] characters?
Below the simple example
import 'dart:convert';
void main() {
final numJson = '1';
encode(numJson);
decode(numJson);
final strJson = 'a';
encode(strJson);
decode(strJson);
}
void encode(value) {
try {
final enc = json.encode(value);
print('enc = $enc');
} on Exception catch(e) {
print(e.toString());
}
}
void decode(value) {
try {
final dec = json.decode(value);
print('dec = $dec');
} on Exception catch(e) {
print(e.toString());
}
}
This is the output:
enc = "1"
dec = 1
enc = "a"
FormatException: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Why dart could not decode JSON ecoded String as String? Don't you think it is a bug?
Solution 1:[1]
It's because your code is incorrect.
The following code is correct, but it is also meaningless, just like your code.
import 'dart:convert';
void main() {
final numJson = '1';
encode(numJson);
decode(numJson);
final strJson = '"a"';
encode(strJson);
decode(strJson);
}
void encode(value) {
try {
final enc = json.encode(value);
print('enc = $enc');
} on Exception catch (e) {
print(e.toString());
}
}
void decode(String value) {
try {
final dec = json.decode(value);
print('dec = $dec');
} on Exception catch (e) {
print(e.toString());
}
}
Output:
enc = "1"
dec = 1
enc = "\"a\""
dec = a
P.S.
I can't even imagine how you thought of writing such an algorithm.
Because it doesn't make any sense.
This algorithm is useless because it doesn't convert the results from one to the other.
Below is a code that does not have this drawback and actually calculates at least something.
import 'dart:convert';
import 'package:test/test.dart';
void main() {
_test('1', 1);
_test('"a"', 'a');
_test('{"a":1}', {'a': 1});
_test('[1,"a"]', [1, 'a']);
}
dynamic decode(String value) {
try {
final dec = json.decode(value);
//print('dec = $dec');
return dec;
} on Exception catch (e) {
print(e.toString());
rethrow;
}
}
String encode(value) {
try {
final enc = json.encode(value);
//print('enc = $enc');
return enc;
} on Exception catch (e) {
print(e.toString());
rethrow;
}
}
void _test(String json, value) {
test('$json <=> $value', () {
final v1 = decode(json);
final v2 = encode(value);
final v3 = decode(v2);
final v4 = encode(v3);
final v5 = decode(v4);
final v6 = encode(v5);
expect(json, v2);
expect(value, v1);
expect(v1, v3);
expect(v2, v4);
expect(v3, v5);
expect(v4, v6);
expect(v5, value);
expect(v6, json);
});
}
Output:
00:00 +0: 1 <=> 1
00:00 +1: "a" <=> a
00:00 +2: {"a":1} <=> {a: 1}
00:00 +3: [1,"a"] <=> [1, a]
00:00 +4: All tests passed!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
