Search⌘ K
AI Features

JSON and Serialization

Explore how to decode JSON strings to Dart objects and encode Dart objects back to JSON in Flutter. Understand the importance of creating model classes for type safety and auto-completion. Discover how code generation libraries reduce boilerplate for complex serialization tasks and improve data handling in Flutter apps.

JSON is a simple text format for representing structured objects and collections. In most cases, when fetching and posting data to remote sources or even storing data locally, we’ll find ourselves needing to convert data to and from JSON. Therefore, understanding how to work with JSON is an invaluable skill since we’ll rarely build an app that doesn’t communicate with remote data or at least store data locally.

Decoding and encoding JSON

We use jsonDecode() to convert a JSON-encoded string to a Dart object and jsonEncode() to convert a Dart object to a JSON-encoded string.

To use either of the functions, we have to import the dart:convert library.

Decoding JSON

Run the code snippet below:

Dart
import 'dart:convert';
void main(){
var jsonString = '''
{
"name": "John Doe",
"email": "johndoe@domain.com",
"age": 34
}
''';
var user = jsonDecode(jsonString);
print('Hello, ${user['name']}!');
print('We sent the verification link to ${user['email']}.');
}

We decode the JSON string into a Dart map containing the user’s ...