In Flutter, JSON (JavaScript Object Notation) serialization is a technique used to convert JSON data into Dart objects and vice versa. This process is essential when working with API responses that are typically returned in JSON format. One popular package for making API calls in Flutter is Dio, which provides a convenient way to handle network requests and responses.
To use JSON serialization with Dio, follow these steps:
- Add the
json_serializable
andbuilt_value
dependencies to yourpubspec.yaml
file:
dependencies:
json_serializable: ^4.5.0
built_value: ^7.1.0
- Create a model class representing the data structure of the API response. For example, let’s say we have an endpoint that returns a user’s profile information in JSON format:
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
part 'user_profile.g.dart';
abstract class UserProfile implements Built<UserProfile, UserProfileBuilder> {
String get name;
String get email;
UserProfile._();
factory UserProfile([void Function(UserProfileBuilder) updates]) = _$UserProfile;
static Serializer<UserProfile> get serializer => _$userProfileSerializer;
}
- Run the following command in your terminal to generate the necessary serialization code:
flutter packages pub run build_runner build
This command generates the serialization code based on the annotations in your model class.
- In your Dio API call, specify the response type as your model class:
final response = await dioClient.get('/user/profile');
final parsedResponse = UserProfile.fromJson(response.data);
Now, the API response will be automatically converted into an instance of the UserProfile
class.
- To send JSON data in the request body, you can convert your Dart object into a JSON string using serialization:
final user = UserProfile((b) => b
..name = 'John Doe'
..email = 'johndoe@example.com'
);
final jsonString = json.encode(user);
In this example, the UserProfile
object is converted into a JSON string using the json.encode
function.
By utilizing JSON serialization with the Dio package in Flutter, handling API responses and sending data to the server becomes much more straightforward and efficient.
Remember to include the necessary import statements for the packages used in your code.
That’s it! You’ve learned how to use JSON serialization with the Dio package in Flutter. Happy coding!