Simple way convert object to json in Dart

Kiolk - Jul 15 - - Dev Community

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;
Enter fullscreen mode Exit fullscreen mode

that included in standard Dart SDK.

To convert from string to object, you can use method:

jsonDecode(jsonString)
Enter fullscreen mode Exit fullscreen mode

for opposite operation, you should use:

jsonEncode(someObject)
Enter fullscreen mode Exit fullscreen mode

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}}
 }
Enter fullscreen mode Exit fullscreen mode

Of course, more information you can find in documentation.

. . . . . . . . . . . . . . . . .
Terabox Video Player