Reputation: 5739
Can you please show how to serialize/desierialize a map<> to/from json in dart? For example, here's a simple data Class:
class SimpleData {
int _blah;
String _str;
SimpleData([this._blah, this._str]);
SimpleData.fromJson(Map<String, dynamic> json) {
_blah = json['b'];
_str = json['s'];
}
Map<String, dynamic> toJson() => {
'b' : _blah,
's' : _str,
};
}
Here's the SimpleData class used in a map:
class MapTest {
Map<int, SimpleData> _mapHell = Map<int, SimpleData>();
MapTest() {
_mapHell[1] = SimpleData(42, "Astfgl");
_mapHell[666] = SimpleData(1234, "Vassenego");
}
MapTest.fromJson(Map<String, dynamic> json) {
_mapHell = jsonDecode(json['coworkers']);
}
Map<String, dynamic> toJson() => {
'coworkers' : jsonEncode(_mapHell),
};
}
Now, when calling MapTest.toJson()
, the following error is thrown:
Converting object to an encodable object failed: _LinkedHashMap len:2
Do you have any ideas whats wrong with the toJson()/fromJson()
methods?
Thank you.
Upvotes: 10
Views: 4607
Reputation: 2832
The encoding/decoding is correct, only that JSON only allows strings as the key.
Change _mapHell
to Map<String, SimpleData>
will work fine.
class MapTest {
final _mapHell = Map<String, SimpleData>(); // Change the Map type
MapTest() {
_mapHell['1'] = SimpleData(42, "Astfgl"); // Use int, ie: '1'
_mapHell['666'] = SimpleData(1234, "Vassenego");
}
MapTest.fromJson(Map<String, dynamic> json) {
_mapHell = jsonDecode(json['coworkers']);
}
Map<String, dynamic> toJson() => {
'coworkers' : jsonEncode(_mapHell),
};
}
Upvotes: 5