What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format. It's easy for humans to read and write, and easy for machines to parse and generate. In Dart, JSON is commonly used for API communication, configuration files, and data storage. The dart:convert library provides built‑in support for JSON encoding and decoding.
Basic JSON Operations
Dart's dart:convert library provides two core functions: jsonDecode to parse a JSON string into a Dart object, and jsonEncode to convert a Dart object back to a JSON string.
Parsing JSON to Dart Objects
While working with raw maps is fine for simple cases, for larger applications you'll want to convert JSON into typed Dart objects (classes). This gives you type safety and better code organization.
Handling Nested JSON
Real‑world JSON often contains nested objects and arrays. You can handle these by creating corresponding classes and using them inside the fromJson and toJson methods.
Working with Lists of Objects
When the JSON contains an array of objects, you can map each element to your Dart class.
Error Handling
JSON parsing can fail if the data is malformed or if the structure doesn't match expectations. Always handle exceptions.
Using json_serializable (Code Generation)
Manually writing fromJson and toJson methods can become tedious, especially for large classes. The json_serializable package generates these methods for you. Add the following dependencies to your pubspec.yaml:
Then annotate your class with @JsonSerializable() and use the generated part file.
Run dart run build_runner build to generate the user.g.dart file containing the serialization logic.
Key Takeaways
- Use
jsonDecodeto parse JSON strings andjsonEncodeto convert objects to JSON.
- Use
- Create factory constructors (
fromJson) andtoJsonmethods to convert between JSON and Dart objects.
- Create factory constructors (
- Handle nested JSON by creating corresponding nested classes.
- Always catch
FormatExceptionwhen parsing JSON from external sources.
- Always catch
- For larger projects, use
json_serializableto automate boilerplate serialization code.
- For larger projects, use