I want to share simple way how convert dart object to string and back. Certainly, you can use special library for it. But in my case, you can use only
library dart.convert;
that included in standard Dart SDK.
To convert from string to object, you can use method:
jsonDecode(jsonString)
for opposite operation, you should use:
jsonEncode(someObject)
If your object contains more complex structures inside than simple types, you should provide additional methods, like in the example below.
class CustomClass {
final String text;
final int value;
CustomClass({required this.text, required this.value});
CustomClass.fromJson(Map<String, dynamic> json)
: text = json['text'],
value = json['value'];
static Map<String, dynamic> toJson(CustomClass value) =>
{'text': value.text, 'value': value.value};
}
void main() {
final CustomClass cc = CustomClass(text: 'Dart', value: 123);
final jsonText = jsonEncode({'cc': cc},
toEncodable: (Object? value) => value is CustomClass
? CustomClass.toJson(value)
: throw UnsupportedError('Cannot convert to JSON:$value'));
print(jsonText); // {"cc":{"text":"Dart","value":123}}
}
Of course, more information you can find in documentation.
Top comments (2)
Looks good, but maybe be more clean from "Utilities" and not an object instance.
Sure, but for different classes this methods will look different. Third-party libraries do same, generate they own implementation of this methods.