I never liked the way Dart developers used to serialize objects by creating a factory constructor, as this way doesn't provide a base class for serialization.
Providing a base class is the OOP way of doing things, as it will be enough to send a Serializable object to the caching function or the HTTP send method as the request body, and the method will handle it.
In a language like C# this is not needed as any object can be serialized via reflection, which dart language abandoned in favor of tree-shaking.
Trying to use Generics to implement it failed as dart language doesn't support creating a new object of generic type new T(), solved by requiring a creator callback as a parameter
class Model1 extends Serializable{
String? stringField;
int? intField;
double? doubleField;
bool? boolField;
@override
void fromMap(Map<String, dynamic> map) {
stringField = map['stringField'];
intField = map['intField'];
doubleField = map['doubleField'];
boolField = map['boolField'];
}
@override
Map<String, dynamic> toMap() {
final Map<String, dynamic> map = <String, dynamic>{};
map['stringField'] = stringField;
map['intField'] = intField;
map['doubleField'] = doubleField;
map['boolField'] = boolField;
return map;
}
}
void main() {
var model = Model1()
..stringField='abc'
..intField=4
..doubleField=3.6
..boolField=true;
var json = Serializable.serializeObject(model);
print(json);
var deserializedModel = Serializable.deserializeObject(json, ()=> Model1());
print(deserializedModel);
}The output would be
{"stringField":"abc","intField":4,"doubleField":3.6,"boolField":true}
{"stringField":"abc","intField":4,"doubleField":3.6,"boolField":true}
For lists
var jsonList = '[{"stringField":"abc","intField":4,"doubleField":3.6,"boolField":true}, {"stringField":"def","intField":5,"doubleField":3.8,"boolField":false}]';
var list = Serializable.deserializeList(jsonList, ()=> Model1());
print(list);Any generator can be used, but you need to change the created methods to conform to the fromMap and toMap required by Serializable base, or use this utility which is a cmd app created in .Net