Sub topic 9
JSON with fromJson and toJson
This chapter adds JSON conversion to a freezed class. You will generate fromJson and toJson, rename and default fields, handle nested objects, and diagnose the errors that decoding produces. It assumes you have already set up freezed, json_serializable and build_runner, and that you can declare a freezed class with a part directive.
Why freezed delegates JSON to json_serializable
freezed does not generate JSON code itself. It generates the class members: equality, toString, copyWith and the union constructors. The conversion code comes from json_serializable, which reads the same class and writes a second generated file.
That gives you two generated files per model:
| File | Produced by | Contents |
|---|---|---|
| `person.freezed.dart` | freezed | `copyWith`, `==`, `hashCode`, `toString`, the `_Person` class |
| `person.g.dart` | json_serializable | `_$PersonFromJson` and `_$PersonToJson` |
Both files come from one dart run build_runner build run. If either part directive is missing, that generator's output is not linked in and the class does not compile.
Adding fromJson
Add two things to a freezed class: the part 'person.g.dart'; directive and a fromJson factory that calls the generated function.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
part 'person.g.dart';
@freezed
abstract class Person with _$Person {
const factory Person({
required String name,
@Default(0) int age,
@JsonKey(name: 'e_mail') String? email,
}) = _Person;
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
}Three details are worth knowing:
fromJsonis a factory you write yourself. It is one line, and it only forwards to the generated_$PersonFromJson.- You do not write
toJson. freezed sees that the class has afromJsonfactory and adds atoJson()method to the generated class. The_$Personmixin exposes it, soperson.toJson()works. - The name after
_$andFrommust match the class name exactly. For a classPerson, the function is_$PersonFromJson.
Running the round trip
The following program decodes a JSON string, changes the value, and encodes it again. Save the class above as person.dart, run the generator, and put this file next to it.
import 'dart:convert';
import 'person.dart';
void main() {
const source = '{"name": "Ada", "age": 36, "e_mail": "[email protected]"}';
final map = jsonDecode(source) as Map<String, dynamic>;
final ada = Person.fromJson(map);
print(ada); // Person(name: Ada, age: 36, email: [email protected])
final older = ada.copyWith(age: 37);
print(jsonEncode(older.toJson()));
// {"name":"Ada","age":37,"e_mail":"[email protected]"}
}jsonDecode returns dynamic, so the cast to Map<String, dynamic> is required. fromJson takes a map, not a string. Keeping the string parsing outside the model means the model stays easy to test with plain maps.
Field-level control with @JsonKey
The @JsonKey annotation goes on a factory parameter. The options you will use most often are these:
namesets the key used in the JSON, as'e_mail'does above. The Dart field keeps its own name.defaultValuesupplies a value when the key is missing. In a freezed class, prefer@Default, which also sets the constructor default.includeFromJson: falseandincludeToJson: falseskip a field in one direction.unknownEnumValuepicks a fallback enum value when the JSON contains a name your enum does not have.
If every key in your API uses snake case, you can avoid annotating each field. Set a rule once in build.yaml:
targets:
$default:
builders:
json_serializable:
options:
field_rename: snake
explicit_to_json: truefield_rename: snake maps firstName to first_name. An explicit @JsonKey(name: ...) on a field still takes priority over this rule. The explicit_to_json option is explained in the next section.
How missing, null and wrong values behave
Generated fromJson code is strict about types and lenient about defaults. These rules cover most surprises:
- A
requirednon-nullable field with a missing ornullkey throws aTypeError(or aCheckedFromJsonExceptionif you enablechecked: true). - A nullable field with a missing key becomes
null. - A field with
@Defaultuses its default when the key is missing ornull. - A wrong type, such as a string where an
intis expected, throws. - A JSON number like
36.0decoded into anintfield is converted withtoInt(), so it works. A string"36"is not converted.
For toJson, null fields are written as null entries by default. To omit them, set includeIfNull: false on the field's @JsonKey, or use @JsonSerializable(includeIfNull: false) as a class-level option.
Nested objects, lists and built-in types
json_serializable knows how to convert several types without extra code:
String,int,double,bool,num, andnullfor nullable fields.List,SetandMap<String, T>of supported types.DateTime, written as an ISO 8601 string.- Enums, written as the enum name (override with
@JsonValue). - Other classes that have
fromJsonandtoJson, which includes your freezed classes.
A model that contains another freezed model only needs both classes to have a fromJson factory:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user.freezed.dart';
part 'user.g.dart';
enum Role {
admin,
member,
}
@freezed
abstract class Address with _$Address {
const factory Address({required String city}) = _Address;
factory Address.fromJson(Map<String, dynamic> json) =>
_$AddressFromJson(json);
}
@freezed
abstract class User with _$User {
const factory User({
required String name,
required Address address,
@Default(<String>[]) List<String> tags,
@JsonKey(unknownEnumValue: Role.member) @Default(Role.member) Role role,
DateTime? joinedAt,
}) = _User;
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}Decoding the nested address works without further setup. Encoding has one catch. Without explicit_to_json: true, the generated toJson puts the Address object itself into the map instead of calling address.toJson(). jsonEncode hides this, because it calls toJson on objects it does not recognize. But the map is not plain JSON data. Comparing it in a test, or passing it to a package that expects only maps and lists, fails. Setting explicit_to_json: true in build.yaml, as shown earlier, fixes this for the whole project.
JSON for sealed unions
A freezed sealed union can also have fromJson. Because the JSON must say which constructor to use, freezed adds a discriminator key named runtimeType and writes the constructor name as its value. For example, LoadState.loading() is written as {"runtimeType": "loading"}.
You can change this with the @Freezed annotation:
@Freezed(unionKey: 'type')renames the discriminator key.@Freezed(unionValueCase: FreezedUnionCase.snake)changes the case of the values.@FreezedUnionValue('custom_name')on a single constructor sets its value directly.
If the JSON contains a value that matches no constructor, decoding throws a CheckedFromJsonException. To avoid this, use @Freezed(fallbackUnion: 'error') to name a constructor that handles unknown values. That constructor must have no required parameters that cannot be filled from the JSON.
Common mistakes
- Missing
part 'x.g.dart';. The analyzer reports that_$PersonFromJsonis not defined. Add the directive and rebuild. - A
.g.dartfile that is out of date. If you add a field andtoJsonignores it, the generated file is stale. Rerun the build, or usedart run build_runner watchwhile developing. - Annotating the wrong place.
@JsonKeybelongs on the factory parameter, not on a getter or a separate field declaration. - A nested class without
fromJson. The error appears when you build, and it names the field whose type cannot be converted. - Date formats that are not ISO 8601. The default
DateTimeconversion fails on them. Write a customJsonConverterfor such fields.
Exercise
A freezed class Product has the field @Default(1) int quantity. You decode {"name": "Pen"} and {"name": "Pen", "quantity": null}. What is quantity in each case, and what happens when you decode {"quantity": 2} with no name, assuming name is required String?
Show answer
In both of the first two cases quantity is 1, because the generated code uses the default when the key is missing or null. Decoding {"quantity": 2} throws a TypeError, since the non-nullable required field name has no value and no default.
Exercise
Your API returns {"user_name": "Ada"}, but your Dart field should be userName. Give two ways to make fromJson read it correctly.
Show answer
Annotate the parameter with @JsonKey(name: 'user_name') required String userName, or set field_rename: snake in the json_serializable options in build.yaml and rebuild. An explicit @JsonKey(name: ...) overrides the global rule if both are present.