Converting class objects to JSON string

  • Usage
    
                  import 'dart:convert';
    
                  // Example class representing an object
                  class Person {
                    final String name;
                    final int age;
    
                    Person({required this.name, required this.age});
    
                    // Convert the object to a JSON format
                    Map<String, dynamic> toJson() {
                      return {
                        'name': name,
                        'age': age,
                      };
                    }
                  }
    
                  void main() {
                    // Create an instance of the Person class
                    Person person = Person(name: 'John', age: 30);
    
                    // Convert the object to JSON
                    String jsonStr = jsonEncode(person.toJson());
    
                    // Print the JSON string
                    print(jsonStr);
                  }