Effortless JSON Serialization with json_serializable
Published on by Flutter News Hub
Transforming data to and from JSON is a breeze with the json_serializable package. Let's explore how to leverage its features and enhance your Dart code.
Annotation Simplified
To enable JSON serialization, simply annotate your classes with @JsonSerializable. This annotation instructs the code generator to create toJson and fromJson methods for you.
Consider the following Person class:
import 'package:json_annotation/json_annotation.dart'; @JsonSerializable() class Person { final String firstName, lastName; final DateTime? dateOfBirth; Person({required this.firstName, required this.lastName, this.dateOfBirth}); factory Person.fromJson(Map json) => _$PersonFromJson(json); Map toJson() => _$PersonToJson(this); }
Customizing Serialization
You can tailor the serialization process by annotating fields with @JsonKey. Specify options like:
- ignore: Exclude the field from serialization.
- name: Override the JSON property name.
- defaultValue: Set a default value for the field if it's missing in JSON.
For instance, to ignore the dateOfBirth field and override the firstName property name in the JSON:
@JsonSerializable() class Person { final String firstName, lastName; @JsonKey(ignore: true) final DateTime? dateOfBirth; Person({required this.firstName, required this.lastName, this.dateOfBirth}); factory Person.fromJson(Map json) => _$PersonFromJson(json); Map toJson() => _$PersonToJson(this); }
Custom Encoders and Decoders
Need more control over serialization? Define custom converters to handle specific types or scenarios. Implement the JsonConverter interface and annotate the field or class:
class EpochDateTimeConverter implements JsonConverter { @override DateTime fromJson(int json) => DateTime.fromMillisecondsSinceEpoch(json); @override int toJson(DateTime object) => object.millisecondsSinceEpoch; } @JsonSerializable() class Person { final String firstName, lastName; @EpochDateTimeConverter() final DateTime? dateOfBirth; Person({required this.firstName, required this.lastName, this.dateOfBirth}); factory Person.fromJson(Map json) => _$PersonFromJson(json); Map toJson() => _$PersonToJson(this); }
Build Configuration
Configure the code generation process through build.yaml:
targets: $default: builders: json_serializable: options: generic_argument_factories: false # Disable factory for generic arguments include_if_null: true # Include null values in JSON
Conclusion
json_serializable empowers you to handle JSON serialization with ease. Leverage its features to simplify data handling in your Dart applications, ensuring seamless interactions with external systems and data sources.