Skip to content

Instantly share code, notes, and snippets.

@Vloz
Created April 28, 2014 07:15
Show Gist options
  • Save Vloz/11363954 to your computer and use it in GitHub Desktop.
Save Vloz/11363954 to your computer and use it in GitHub Desktop.
Example of use of reviver and toEncodable functions, to encode and decode a JSON with a List of Object in dart
class MyListClass{
String value;
List<MyItemClass> items;
MyListClass(){}
MyListClass.fromRaw(Map value){
value = JSON.decode(value['value']);
items = JSON.decode(value['items'],reviver:(k,v){
if(v is Map) //Parse every Map found as a MyItemClass
return new MyItemClass.fromRaw(v);
return v; //Return every other object as they are (list, properties...)
});
}
Map toJson() {
return{
'value':JSON.encode(value),
'items':JSON.encode(items,toEncodable: (v){
if(v is MyItemClass)
return v.toJson();
return v;
})
};
}
}
class MyItemClass{
String val1;
String val2;
Contact(){}
MyItemClass.fromRaw(Map value){
val1 = JSON.decode(value['val1']);
val2 = JSON.decode(value['val2']);
}
Map toJson() {
return{
'val1':JSON.encode(val1),
'val2':JSON.encode(val2)
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment