Mastering JSON Serialization in Flutter: A Comprehensive Guide

Understanding JSON Serialization

JSON (JavaScript Object Notation) is the standard for transferring typed data between systems. In Flutter, parsing JSON strings is a crucial task, but it can be challenging due to the lack of reflection at runtime.

JSON serialization involves converting a data object from its native language type to a JSON string. This process is essential when interacting with APIs or storing data locally. There are two primary actions in JSON serialization:

  • Serialization: Converting a data object to a JSON string.
  • Deserialization: Converting a JSON string back to a native object.

Challenges of JSON Serialization in Flutter

Unlike other languages, Flutter doesn’t support runtime reflection, making JSON serialization more difficult. Reflection allows languages to inspect objects and generate code dynamically. Without reflection, Flutter requires more manual effort to serialize and deserialize JSON data.

Serializing a Class with JSON in Flutter

To serialize a class in Flutter, you can use the json package. Let’s create a simple Favorite class:

class Favorite {
  String title;
  String artist;

  Favorite({required this.title, required this.artist});

  factory Favorite.fromJson(Map<String, dynamic> json) {
    return Favorite(
      title: json['title'],
      artist: json['artist'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'title': title,
      'artist': artist,
    };
  }
}

In this example, we’ve added fromJson and toJson methods to handle serialization and deserialization.

Automatically Generating JSON Handling Code

While manual serialization works, it can be tedious and error-prone. A better approach is to use packages like json_serializable to generate JSON handling code automatically.

First, add json_serializable to your pubspec.yaml file:

dependencies:
  json_serializable: ^6.5.4

dev_dependencies:
  build_runner: ^2.2.0
  json_serializable_generator: ^6.5.4

Then, annotate your class with @JsonSerializable():

import 'package:json_annotation/json_annotation.dart';

part 'favorite.g.dart';

@JsonSerializable()
class Favorite {
  String title;
  String artist;

  Favorite({required this.title, required this.artist});

  factory Favorite.fromJson(Map<String, dynamic> json) => _$FavoriteFromJson(json);

  Map<String, dynamic> toJson() => _$FavoriteToJson(this);
}

Run the following command to generate the JSON handling code:

flutter pub run build_runner build --delete-conflicting-outputs

This will create a favorite.g.dart file containing the generated code.

Deserializing JSON Data from a Remote Source

When working with APIs, you’ll often receive JSON data that needs to be deserialized. You can use online tools like JSON to Dart converters to generate the necessary classes.

Let’s assume we have a JSON response from an API:

{
  "activity": "Watch a movie",
  "type": "relaxation",
  "participants": 1,
  "price": 0.0,
  "link": "",
  "key": "123456",
  "accessibility": 0.0
}

We can generate the corresponding Dart class using a JSON to Dart converter:

class BoredAPI {
  String activity;
  String type;
  int participants;
  double price;
  String link;
  String key;
  double accessibility;

  BoredAPI({
    required this.activity,
    required this.type,
    required this.participants,
    required this.price,
    required this.link,
    required this.key,
    required this.accessibility,
  });

  factory BoredAPI.fromJson(Map<String, dynamic> json) {
    return BoredAPI(
      activity: json['activity'],
      type: json['type'],
      participants: json['participants'],
      price: json['price'],
      link: json['link'],
      key: json['key'],
      accessibility: json['accessibility'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'activity': activity,
      'type': type,
      'participants': participants,
      'price': price,
      'link': link,
      'key': key,
      'accessibility': accessibility,
    };
  }
}

With this generated class, we can now deserialize the JSON data and use it in our Flutter app.

Leave a Reply