Home  • Programming • Dart

How to convert an object into JSON string in Dart?


employee_model.dart
class Employee {
  final int id;
  final String name;
  final String department;
  final Address? address;

  Employee({
    required this.id,
    required this.name,
    required this.department,
    required this.address,
  });

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'department': department,
      'address': address.toJson(),
    };
  }
}
address_model.dart - A nested object
class Address {
  final String city;

  Address({required this.city});

  Map<String, dynamic> toJson() {
    return {
      'city': city,
    };
  }
}
main.dart
import 'dart:convert';

void main() {
  Employee emp = Employee(
    id: 1,
    name: 'John',
    department: 'HR',
    address: Address(
      city: 'Dhaka',
      country: 'Bangladesh',
    ),
  );

  String jsonString = jsonEncode(emp.toJson());
  print(jsonString);

}
Note: .map((e) => e.toJson()) Convert each object → Map Output
{
  "id":1,
  "name":"John",
  "department":"HR",
  "address":{
    "city":"Dhaka",
    "country":"Bangladesh"
  }
}

Comments 0


Copyright © 2026. Powered by Intellect Software Ltd