---
title: "How do you use json_serializable in Flutter?"
description: "Annotate a Dart class with @JsonSerializable, add fromJson and toJson, and run build_runner to generate the conversion code for JSON parsing."
url: "https://bugsee.com/answers/flutter/flutter-json-serializable/"
---

# How do you use json_serializable in Flutter?

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

```dart
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);
}
```

```bash
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

- [What is build_runner in Flutter and how do you use it?](https://bugsee.com/answers/flutter/flutter-build-runner/)
