Handling JSON data in Dart primarily involves two steps: parsing and encoding. Dart provides the built-in json library to handle these operations. Below are the specific steps and examples:
1. Import the dart:convert library
First, you need to import Dart's dart:convert library, which contains the tools required for handling JSON:
dartimport 'dart:convert';
2. JSON Parsing (Decoding)
Convert JSON strings to Dart Maps or Lists. This is typically used when retrieving API response data:
dartString jsonString = '{"name": "John", "age": 30}'; Map<String, dynamic> user = jsonDecode(jsonString); print(user['name']); // Output: John print(user['age']); // Output: 30
If JSON is an array:
dartString jsonArray = '[{"name": "John"}, {"name": "Jane"}]'; List<dynamic> users = jsonDecode(jsonArray); print(users[0]['name']); // Output: John print(users[1]['name']); // Output: Jane
3. JSON Encoding (Serialization)
Convert Dart Maps or Lists to JSON strings. This is typically used for sending data to servers:
dartMap<String, dynamic> data = {'name': 'John', 'age': 30}; String json = jsonEncode(data); print(json); // Output: {"name":"John","age":30}
4. Handling Complex JSON Structures
For more complex JSON structures, you may need to create model classes to represent the data and use libraries like json_serializable to simplify serialization and deserialization.
For example, create a User class and use json_serializable to automatically generate related JSON processing code:
dartimport 'package:json_annotation/json_annotation.dart'; part 'user.g.dart'; () class User { String name; int age; User({required this.name, required this.age}); factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json); Map<String, dynamic> toJson() => _$UserToJson(this); }
Then, run the build command in your build_runner to generate the auto-generated code.
These steps outline the basic methods for handling JSON data in Dart. Using built-in functions and libraries can efficiently handle common data exchange formats in web development.