JSON and Serialization
Learn to encode and decode data in Flutter.
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:
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 ...