DEV Community

Cover image for Simple way convert object to json in Dart
Kiolk
Kiolk

Posted on

Simple way convert object to json in Dart

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.

Top comments (2)

Collapse
 
sazardev profile image
Sazardev

Looks good, but maybe be more clean from "Utilities" and not an object instance.

Collapse
 
kiolk profile image
Kiolk • Edited

Sure, but for different classes this methods will look different. Third-party libraries do same, generate they own implementation of this methods.