— Dart, JSON, Serialization, Flutter — 1 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.
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}
To serialize and deserialize our Book
class, we'll add two methods: toJson
and fromJson
.
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
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}
To demonstrate serialization and deserialization, consider the following example:
1import 'dart:convert';2
3void main() {4 // Creating a book instance5 var book = Book(title: '1984', author: 'George Orwell', publicationYear: 1949);6
7 // Serializing the book to JSON8 String jsonBook = jsonEncode(book.toJson());9 print('Serialized Book: $jsonBook');10
11 // Deserializing back to a book object12 Map<String, dynamic> decodedJson = jsonDecode(jsonBook);13 Book newBook = Book.fromJson(decodedJson);14 print('Deserialized Book: Title - ${newBook.title}, Author - ${newBook.author}');15}