text stringlengths 1 474 |
|---|
json_serializable and built_value. |
How do you choose between these packages? |
The json_serializable package allows you to make regular |
classes serializable by using annotations, |
whereas the built_value package provides a higher-level way |
of defining immutable value classes that can also be |
serialized to JSON.Since the serialization code is not handwritten or maintained manually |
anymore, you minimize the risk of having JSON serialization exceptions at |
runtime.<topic_end> |
<topic_start> |
Setting up json_serializable in a project |
To include json_serializable in your project, you need one regular |
dependency, and two dev dependencies. In short, dev dependencies |
are dependencies that are not included in our app source code—they |
are only used in the development environment.To add the dependencies, run flutter pub add:Run flutter pub get inside your project root folder |
(or click Packages get in your editor) |
to make these new dependencies available in your project.<topic_end> |
<topic_start> |
Creating model classes the json_serializable way |
The following shows how to convert the User class to a |
json_serializable class. For the sake of simplicity, |
this code uses the simplified JSON model |
from the previous samples.user.dart |
<code_start>import 'package:json_annotation/json_annotation.dart'; |
/// This allows the `User` class to access private members in |
/// the generated file. The value for this is *.g.dart, where |
/// the star denotes the source file name. |
part 'user.g.dart'; |
/// An annotation for the code generator to know that this class needs the |
/// JSON serialization logic to be generated. |
@JsonSerializable() |
class User { |
User(this.name, this.email); |
String name; |
String email; |
/// A necessary factory constructor for creating a new User instance |
/// from a map. Pass the map to the generated `_$UserFromJson()` constructor. |
/// The constructor is named after the source class, in this case, User. |
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json); |
/// `toJson` is the convention for a class to declare support for serialization |
/// to JSON. The implementation simply calls the private, generated |
/// helper method `_$UserToJson`. |
Map<String, dynamic> toJson() => _$UserToJson(this); |
}<code_end> |
With this setup, the source code generator generates code for encoding |
and decoding the name and email fields from JSON.If needed, it is also easy to customize the naming strategy. |
For example, if the API returns objects with snake_case, |
and you want to use lowerCamelCase in your models, |
you can use the @JsonKey annotation with a name parameter:It’s best if both server and client follow the same naming strategy. |
@JsonSerializable() provides fieldRename enum for totally converting dart |
fields into JSON keys.Modifying @JsonSerializable(fieldRename: FieldRename.snake) is equivalent to |
adding @JsonKey(name: '<snake_case>') to each field.Sometimes server data is uncertain, so it is necessary to verify and protect data |
on client. |
Other commonly used @JsonKey annotations include:<topic_end> |
<topic_start> |
Running the code generation utility |
When creating json_serializable classes the first time, |
you’ll get errors similar to what is shown in the image below.These errors are entirely normal and are simply because the generated code for |
the model class does not exist yet. To resolve this, run the code |
generator that generates the serialization boilerplate.There are two ways of running the code generator.<topic_end> |
<topic_start>One-time code generation |
By running dart run build_runner build --delete-conflicting-outputs in the project root, |
you generate JSON serialization code for your models whenever they are needed. |
This triggers a one-time build that goes through the source files, picks the |
relevant ones, and generates the necessary serialization code for them.While this is convenient, it would be nice if you did not have to run the |
build manually every time you make changes in your model classes.<topic_end> |
<topic_start>Generating code continuously |
A watcher makes our source code generation process more convenient. It |
watches changes in our project files and automatically builds the necessary |
files when needed. Start the watcher by running |
dart run build_runner watch --delete-conflicting-outputs in the project root.It is safe to start the watcher once and leave it running in the background.<topic_end> |
<topic_start> |
Consuming json_serializable models |
To decode a JSON string the json_serializable way, |
you do not have actually to make any changes to our previous code. |
<code_start>final userMap = jsonDecode(jsonString) as Map<String, dynamic>; |
final user = User.fromJson(userMap);<code_end> |
The same goes for encoding. The calling API is the same as before. |
<code_start>String json = jsonEncode(user);<code_end> |
With json_serializable, |
you can forget any manual JSON serialization in the User class. |
The source code generator creates a file called user.g.dart, |
that has all the necessary serialization logic. |
You no longer have to write automated tests to ensure |
that the serialization works—it’s now |
the library’s responsibility to make sure the serialization works |
appropriately.<topic_end> |
<topic_start> |
Generating code for nested classes |
You might have code that has nested classes within a class. |
If that is the case, and you have tried to pass the class in JSON format |
as an argument to a service (such as Firebase, for example), |
you might have experienced an Invalid argument error.Consider the following Address class: |
<code_start>import 'package:json_annotation/json_annotation.dart'; |
part 'address.g.dart'; |
@JsonSerializable() |
class Address { |
String street; |
String city; |
Address(this.street, this.city); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.