Skip to content
DeveloperMemos

Handling JSON Serialization in Dart with Custom Objects

Dart, JSON, Serialization, Flutter1 min read

In Dart, dealing with JSON data is a common task, especially when working with web services and APIs. However, serializing custom objects to and from JSON can be challenging. This article explores how to handle JSON serialization in Dart, particularly for custom objects.

Defining a Custom Object

Before diving into serialization, let's define a custom object. Consider a Book class with attributes like title, author, and publication year.

1class Book {
2 String title;
3 String author;
4 int publicationYear;
5
6 Book({this.title, this.author, this.publicationYear});
7}

Implementing Serialization Methods

To serialize and deserialize our Book class, we'll add two methods: toJson and fromJson.

The toJson Method

The toJson method converts an instance of Book into a map, which can easily be serialized into a JSON string.

1Map<String, dynamic> toJson() {
2 return {
3 'title': title,
4 'author': author,
5 'publicationYear': publicationYear,
6 };
7}

The fromJson Method

The fromJson static method creates an instance of Book from a map, typically obtained by decoding a JSON string.

1static Book fromJson(Map<String, dynamic> json) {
2 return Book(
3 title: json['title'],
4 author: json['author'],
5 publicationYear: json['publicationYear'],
6 );
7}

Using Serialization Methods

To demonstrate serialization and deserialization, consider the following example:

1import 'dart:convert';
2
3void main() {
4 // Creating a book instance
5 var book = Book(title: '1984', author: 'George Orwell', publicationYear: 1949);
6
7 // Serializing the book to JSON
8 String jsonBook = jsonEncode(book.toJson());
9 print('Serialized Book: $jsonBook');
10
11 // Deserializing back to a book object
12 Map<String, dynamic> decodedJson = jsonDecode(jsonBook);
13 Book newBook = Book.fromJson(decodedJson);
14 print('Deserialized Book: Title - ${newBook.title}, Author - ${newBook.author}');
15}