Home  • Programming • Dart

How to convert JSON string into a model object in Dart?

Sample JSON Response:
{
  "id": 1,
  "name": "John",
  "department": "HR"
}
employee_model.dart
class Employee {
  final int id;
  final String name;
  final String department;

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

  factory Employee.fromJson(Map<String, dynamic> json) {
    return Employee(
      id: json['id'],
      name: json['name'],
      department: json['department'],
    );
  }
}
employee_api_service.dart
import 'dart:convert';
import 'package:http/http.dart' as http;

Future<Employee?> getEmployee(String empId) async {
  final response = await http.get(
    Uri.parse('$baseUrl/api/HR/Person/IdentityCard?id=$empId'),
  );

  if (response.statusCode == 200) {
    final Map<String, dynamic> data =
        jsonDecode(response.body);

    Employee employee = Employee.fromJson(data);

    return employee;
  }

  return null;
}
- jsonDecode(response.body) Converts JSON string → Dart Map - Employee.fromJson(data) Converts Dart Map → Employee object

Comments 0


Copyright © 2026. Powered by Intellect Software Ltd