How do you use json_serializable in Flutter?

← Flutter answers

Annotate the class with @JsonSerializable(), add fromJson and toJson that call the generated functions, and run build_runner to create the .g.dart file.

import 'package:json_annotation/json_annotation.dart';
 
part 'user.g.dart';
 
@JsonSerializable(explicitToJson: true)
class User {
  final String name;
 
  @JsonKey(name: 'email_address')
  final String? email;
 
  final List<Address> addresses;
 
  User({required this.name, this.email, this.addresses = const []});
 
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}
dart run build_runner build --delete-conflicting-outputs

Use explicitToJson: true when the class contains other serializable classes, otherwise nested objects are not converted. @JsonKey handles renamed fields and defaults, and fieldRename: FieldRename.snake converts the whole class at once.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required