Working with JSON in Flutter While Using json_annotations and json_serializable Modules in 2022

John Maeda
4 min readApr 24, 2022

How to use Flutter/Dart’s magical ways to convert JSON data into usable structures so that you can get unstuck — and get going.

Illustration by Midjourney engine

Why are you here?

You have read tons of Medium posts and watched plenty of YouTube videos and still feel a little confused. Along the way, you found various ways to convert JSON into Dart code magically. But … it doesn’t work quite right.

This is the best converter out there, but it’s not perfect. But it does a great job of locating the general ENUMs you might want to use … and also the rough data structure you’ll want to have going forward.

Let’s do this

Follow along in 5-ish steps:

  1. Add three modules to your project from the command-line:

unix% flutter pub add json_serializable

unix% flutter pub add json_annotation

unix% flutter pub add build_runner

and then adjust your pubspec.yaml file by moving two of the entries underneath dev_dependencies to look like so:

Move the two packages you added below “dev_dependencies” and you’re good to go!

2. Any place you intend to use this module you’ll need this header for your file (let’s say the file’s named special.dart):

import 'package:json_annotation/json_annotation.dart';

3. Your special.dart file needs a line of code that reads:

part 'special.g.dart'

Note that weird “.g” you need to add — be sure to match this statement with your actual file name. You’ll thank me later.

4. Each time you define a class manually with data inside it, it should have the format:

@JsonSerializable()class Person {// required vs optional distinction gets made by whether
// you say it's nullable? or not / you'll need to match it
// up with what you stick in your constructor / required
// means it's necessary; and if it's optional, you need
// to nullable? the instance variable explicitly
John Maeda

John Maeda: Technologist and product experience leader that bridges business, engineering, design via working inclusively. Currently VP Design and A.I. at MSFT.