text
stringlengths
1
372
<code_start>
string json = jsonEncode(user);
<code_end>
with this approach, the calling code doesn’t have to worry about JSON
serialization at all. however, the model class still definitely has to.
in a production app, you would want to ensure that the serialization
works properly. in practice, the User.fromJson() and User.toJson()
methods both need to have unit tests in place to verify correct behavior.
info
the cookbook contains a more comprehensive worked example of using
JSON model classes, using an isolate to parse
the JSON file on a background thread. this approach is ideal if you
need your app to remain responsive while the JSON file is being
decoded.
however, real-world scenarios are not always that simple.
sometimes JSON API responses are more complex, for example since they
contain nested JSON objects that must be parsed through their own model
class.
it would be nice if there were something that handled the JSON encoding
and decoding for you. luckily, there is!
<topic_end>
<topic_start>
serializing JSON using code generation libraries
although there are other libraries available, this guide uses
json_serializable, an automated source code generator that
generates the JSON serialization boilerplate for you.
info
choosing a library:
you might have noticed two flutter favorite packages
on pub.dev that generate JSON serialization code,
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,