JSON Serialization in Flutter

JSON Serialization in Flutter

JSON Serialization in Flutter

Introduction

JSON serialization in Flutter involves converting Dart objects to JSON strings (serialization) and JSON data back to Dart objects (deserialization). It is a common approach to exchange data between an application and a backend server or local storage.

Serialization and Deserialization

Serialization: Converts a Dart object into a JSON string.
Deserialization: Parses a JSON string into a Dart object.

Example JSON structure:

{
  "id": 1,
  "name": "Flutter",
  "isAwesome": true
}

Steps for JSON Serialization

1. Define a Dart Class

class Course {
  final int id;
  final String name;
  final bool isAwesome;

  Course({required this.id, required this.name, required this.isAwesome});
}

2. Add Serialization and Deserialization Methods

class Course {
  final int id;
  final String name;
  final bool isAwesome;

  Course({required this.id, required this.name, required this.isAwesome});

  factory Course.fromJson(Map json) {
    return Course(
      id: json['id'],
      name: json['name'],
      isAwesome: json['isAwesome'],
    );
  }

  Map toJson() {
    return {
      'id': id,
      'name': name,
      'isAwesome': isAwesome,
    };
  }
}

3. Use the Methods

void main() {
  String jsonString = '{"id": 1, "name": "Flutter", "isAwesome": true}';
  Map jsonData = jsonDecode(jsonString);
  Course course = Course.fromJson(jsonData);

  print(course.name); // Output: Flutter

  String jsonEncoded = jsonEncode(course.toJson());
  print(jsonEncoded); // Output: {"id":1,"name":"Flutter","isAwesome":true}
}

Using json_serializable Package

1. Add Dependencies

dependencies:
  json_annotation: ^latest_version

dev_dependencies:
  build_runner: ^latest_version
  json_serializable: ^latest_version

2. Define the Class

@JsonSerializable()
class Course {
  final int id;
  final String name;
  final bool isAwesome;

  Course({required this.id, required this.name, required this.isAwesome});

  factory Course.fromJson(Map json) => _$CourseFromJson(json);
  Map toJson() => _$CourseToJson(this);
}

3. Generate Code

flutter pub run build_runner build

4. Use the Generated Code

void main() {
  String jsonString = '{"id": 1, "name": "Flutter", "isAwesome": true}';
  Map jsonData = jsonDecode(jsonString);

  Course course = Course.fromJson(jsonData);
  print(course.name); // Output: Flutter

  String jsonEncoded = jsonEncode(course.toJson());
  print(jsonEncoded); // Output: {"id":1,"name":"Flutter","isAwesome":true}
}

Handling Nested JSON

For nested structures, create additional Dart classes and handle them recursively:

Example JSON

{
  "id": 1,
  "name": "Flutter",
  "topics": [
    {"id": 101, "title": "Widgets"},
    {"id": 102, "title": "State Management"}
  ]
}

Dart Classes

class Topic {
  final int id;
  final String title;

  Topic({required this.id, required this.title});

  factory Topic.fromJson(Map json) => Topic(
    id: json['id'],
    title: json['title'],
  );

  Map toJson() => {
    'id': id,
    'title': title,
  };
}

class Course {
  final int id;
  final String name;
  final List topics;

  Course({required this.id, required this.name, required this.topics});

  factory Course.fromJson(Map json) => Course(
    id: json['id'],
    name: json['name'],
    topics: (json['topics'] as List).map((t) => Topic.fromJson(t)).toList(),
  );

  Map toJson() => {
    'id': id,
    'name': name,
    'topics': topics.map((t) => t.toJson()).toList(),
  };
}

Summary

  • Manual serialization is straightforward but repetitive.
  • Use json_serializable for automated serialization.
  • Handle nested JSON with recursive Dart class structures.

Efficient JSON serialization ensures smooth communication between Flutter apps and external data sources.

Comments

Popular Posts