DEV Community

Cover image for Flutter JSON Parsing: fromJson, Null Safety and Code Generation
Muhammad Naeem
Muhammad Naeem

Posted on Originally published at neemii.dev

Flutter JSON Parsing: fromJson, Null Safety and Code Generation

Almost every Flutter app talks to an API, and almost every API speaks JSON. Dart has no reflection in Flutter, so you can't hand a JSON string to a library and get a typed object back by magic. You either write the mapping yourself or generate it.

This post covers both, in the order you'll meet them: jsonDecode, a hand-written model, the null safety traps, nested objects and lists, json_serializable, freezed, and the error messages that show up when something doesn't match.

Step 1: jsonDecode gives you dynamic data

jsonDecode from dart:convert turns a JSON string into plain Dart values: Map<String, dynamic> for objects, List<dynamic> for arrays, and String, int, double, bool or null for the rest.

import 'dart:convert';

void main() {
  const body = '{"id": 7, "name": "Ayesha", "email": null}';
  final data = jsonDecode(body) as Map<String, dynamic>;
  print(data['name']); // Ayesha
  print(data['id'].runtimeType); // int
}
Enter fullscreen mode Exit fullscreen mode

You could pass data around your app and read data['name'] everywhere. Don't. Every read is untyped, a typo in a key returns null instead of a compile error, and when the API changes you find out from a crash report. Convert it to a class once, at the edge of your app.

Step 2: a model class with fromJson and toJson

The standard pattern is a fromJson factory constructor and a toJson method:

class User {
  const User({required this.id, required this.name, this.email});

  final int id;
  final String name;
  final String? email;

  factory User.fromJson(Map<String, dynamic> json) => User(
        id: json['id'] as int,
        name: json['name'] as String,
        email: json['email'] as String?,
      );

  Map<String, dynamic> toJson() => {
        'id': id,
        'name': name,
        'email': email,
      };
}
Enter fullscreen mode Exit fullscreen mode

Usage:

final user = User.fromJson(data);
print(user.email); // null
print(jsonEncode(user.toJson())); // {"id":7,"name":"Ayesha","email":null}
Enter fullscreen mode Exit fullscreen mode

The as casts are the important part. They are where the type check happens, and they are where your app will throw if the API sends something you didn't expect. That is a good thing: it fails at the parsing line, with a clear message, instead of three screens later.

If you don't want to type these classes by hand, paste a real response into my JSON to Dart converter. It produces this same style of model (plain Dart, json_serializable or freezed), runs in your browser, and doesn't send your JSON anywhere.

Null safety: where most parsing bugs come from

Dart's null safety only protects you after the data is inside a typed field. The cast from dynamic is where you decide what's allowed to be null, and getting that decision wrong is the most common source of crashes.

int vs double

JSON has one number type. Dart has two. jsonDecode('450') gives you an int, and jsonDecode('450.0') gives you a double. Many APIs send prices as 450 one day and 450.5 the next, so this will eventually crash on a phone:

price: json['price'] as double, // throws when the API sends 450
Enter fullscreen mode Exit fullscreen mode

Read every double through num instead:

price: (json['price'] as num).toDouble(),
Enter fullscreen mode Exit fullscreen mode

One detail that makes this bug sneaky: on Flutter web compiled to JavaScript (the default build), int and double are both JavaScript numbers, so 450 as double succeeds. The same line compiled with dart compile js printed 450, while the Dart VM threw. If you test mainly on web, you can ship this bug to Android and iOS without seeing it once.

Missing keys and null values

Reading a key that isn't in the map returns null, the same as a key whose value is null. So json['email'] as String? handles both cases. A field that's required in your class but missing from the response throws:

type 'Null' is not a subtype of type 'String' in type cast
Enter fullscreen mode Exit fullscreen mode

For each field, decide which of three things it is:

  1. Always present: non-nullable type, plain cast (as String).
  2. Sometimes missing, and null means something: nullable type (String?, as String?).
  3. Sometimes missing, but there's a sensible default: nullable cast plus ??.
status: json['status'] as String? ?? 'pending',
Enter fullscreen mode Exit fullscreen mode

Don't make everything nullable just to stop crashes. You'll trade one crash at parse time for ! operators and null checks spread through your UI code. Be strict where the API contract is strict, and loose only where it really is optional.

From my own work: on a government survey app I'm working on (I can't share details), records were getting stuck on some enumerators' devices and never reached the server. I went through the Postman responses, the Grafana logs and the field notes, and found the cause: in a few scenarios a record was missing an ID in the local database, so the JSON the app sent was not what the server expected, and the server rejected it every time the app retried. Making the parser more lenient would only have hidden the problem. Instead I added an auto-repair step that restores any missing survey ID in the local database before upload, so the server accepts the JSON and the stuck records go through. The lesson: when JSON fails, check the data you're serialising, not just the parsing code.

When the API sends the wrong type

Some backends send "id": "42" in one endpoint and "id": 42 in another. If you can't get the backend fixed, read it with a small helper instead of a cast:

int readInt(Object? v) => switch (v) {
      int i => i,
      num n => n.toInt(),
      String s => int.parse(s),
      _ => throw FormatException('Expected an int, got $v'),
    };
Enter fullscreen mode Exit fullscreen mode

Keep these helpers few and deliberate. Each one hides a backend inconsistency that someone should eventually fix.

Nested objects and lists

Real responses are nested. Here's an order with a customer object, a list of items and a list of strings:

{
  "id": 1042,
  "total": 450,
  "customer": {"name": "Sara", "phone": null},
  "items": [
    {"title": "Chai", "qty": 2, "price": 150},
    {"title": "Samosa", "qty": 3, "price": 50.0}
  ],
  "tags": ["express", "paid"]
}
Enter fullscreen mode Exit fullscreen mode

Each nested object gets its own class with its own fromJson. Lists are decoded as List<dynamic>, so you map each element:

factory Order.fromJson(Map<String, dynamic> json) => Order(
      id: json['id'] as int,
      status: json['status'] as String? ?? 'pending',
      total: (json['total'] as num).toDouble(),
      customer: Customer.fromJson(json['customer'] as Map<String, dynamic>),
      items: (json['items'] as List<dynamic>)
          .map((e) => OrderItem.fromJson(e as Map<String, dynamic>))
          .toList(),
      tags: (json['tags'] as List<dynamic>? ?? const [])
          .map((e) => e as String)
          .toList(),
      coupon: json['coupon'] as String?,
    );

Map<String, dynamic> toJson() => {
      'id': id,
      'status': status,
      'total': total,
      'customer': customer.toJson(),
      'items': items.map((e) => e.toJson()).toList(),
      'tags': tags,
      'coupon': coupon,
    };
Enter fullscreen mode Exit fullscreen mode

Customer and OrderItem follow the same pattern as User above, with OrderItem.price read as (json['price'] as num).toDouble(). Note that toJson calls toJson() on the nested objects too, so you get plain maps all the way down.

When the top level is a list

If the endpoint returns an array, cast the decoded value to List<dynamic>:

final users = (jsonDecode(body) as List<dynamic>)
    .map((e) => User.fromJson(e as Map<String, dynamic>))
    .toList();
Enter fullscreen mode Exit fullscreen mode

Many APIs wrap the list instead: {"data": [...], "page": 1}. Then you cast to a map first and read the list from it:

final map = jsonDecode(body) as Map<String, dynamic>;
final users = (map['data'] as List<dynamic>)
    .map((e) => User.fromJson(e as Map<String, dynamic>))
    .toList();
Enter fullscreen mode Exit fullscreen mode

Large responses

Decoding a big response on the main isolate can drop frames. Move the parsing to another isolate with Isolate.run (or Flutter's compute):

List<User> parseUsers(String body) => (jsonDecode(body) as List<dynamic>)
    .map((e) => User.fromJson(e as Map<String, dynamic>))
    .toList();

final users = await Isolate.run(() => parseUsers(body));
Enter fullscreen mode Exit fullscreen mode

The closure and what it captures (here, the body string) are copied into the new isolate, so keep it small and self-contained. Only do this when you've seen jank on a real device; for small payloads it adds overhead without any benefit.

json_serializable: let the generator write fromJson

Writing models by hand is fine for a few classes. Past that, the casts get repetitive and a renamed field is easy to miss in toJson. json_serializable generates both methods from annotations.

Add the packages:

flutter pub add json_annotation dev:build_runner dev:json_serializable
Enter fullscreen mode Exit fullscreen mode

Then annotate the model and point it at the file that will be generated:

import 'package:json_annotation/json_annotation.dart';

part 'product.g.dart';

@JsonSerializable(explicitToJson: true)
class Product {
  const Product({
    required this.id,
    required this.title,
    required this.price,
    this.imageUrl,
    this.inStock = true,
    required this.variants,
  });

  final int id;
  final String title;
  final double price;

  @JsonKey(name: 'image_url')
  final String? imageUrl;

  @JsonKey(name: 'in_stock')
  final bool inStock;

  final List<Variant> variants;

  factory Product.fromJson(Map<String, dynamic> json) =>
      _$ProductFromJson(json);

  Map<String, dynamic> toJson() => _$ProductToJson(this);
}
Enter fullscreen mode Exit fullscreen mode

Variant is another @JsonSerializable() class with the same two one-line methods. Generate the code:

dart run build_runner build --delete-conflicting-outputs
Enter fullscreen mode Exit fullscreen mode

Use watch instead of build to regenerate on every save. The generated product.g.dart reads numbers safely for you:

Product _$ProductFromJson(Map<String, dynamic> json) => Product(
  id: (json['id'] as num).toInt(),
  title: json['title'] as String,
  price: (json['price'] as num).toDouble(),
  imageUrl: json['image_url'] as String?,
  inStock: json['in_stock'] as bool? ?? true,
  variants: (json['variants'] as List<dynamic>)
      .map((e) => Variant.fromJson(e as Map<String, dynamic>))
      .toList(),
);
Enter fullscreen mode Exit fullscreen mode

Things worth knowing:

  • explicitToJson: true matters for nested objects. Without it, toJson() puts the Variant objects themselves in the map, not maps. jsonEncode still works because it calls toJson() on them, but anything else that expects a plain map (a local database, a test comparing maps) will not.
  • Default values in the constructor (this.inStock = true) are used when the key is missing or null.
  • Project-wide settings go in build.yaml at the project root, so you don't repeat them on every class:
targets:
  $default:
    builders:
      json_serializable:
        options:
          explicit_to_json: true
          field_rename: snake
Enter fullscreen mode Exit fullscreen mode

With field_rename: snake, a Dart field fullName maps to the JSON key full_name without a @JsonKey on every field.

The cost is the build step: a part directive in every model, generated files in your repo (or a build step in CI), and a few seconds of waiting after each model change.

freezed: when you want more than JSON

freezed is a different kind of tool. It generates immutable data classes: copyWith, == and hashCode based on values, toString, and sealed unions. For JSON it hands off to json_serializable, so you install both.

import 'package:freezed_annotation/freezed_annotation.dart';

part 'product.freezed.dart';
part 'product.g.dart';

@freezed
abstract class Product with _$Product {
  const factory Product({
    required int id,
    required String title,
    required double price,
    @JsonKey(name: 'image_url') String? imageUrl,
    @JsonKey(name: 'in_stock') @Default(true) bool inStock,
  }) = _Product;

  factory Product.fromJson(Map<String, dynamic> json) =>
      _$ProductFromJson(json);
}
Enter fullscreen mode Exit fullscreen mode

With that you get product.copyWith(price: 1999) and a == b comparing values, which is what state management (Bloc, Riverpod) wants when it decides whether to rebuild.

Two notes for current versions (freezed 3.x). The class must be declared abstract (or sealed for unions), which older tutorials don't show. And @JsonKey on constructor parameters triggers the analyzer warning invalid_annotation_target; freezed's own docs recommend turning it off in analysis_options.yaml:

analyzer:
  errors:
    invalid_annotation_target: ignore
Enter fullscreen mode Exit fullscreen mode

Is it worth it? If you only need to parse API responses and show them, no: json_serializable alone is less generated code and fewer concepts. freezed earns its place when your models are also your app state, when you update them with copyWith a lot, or when you want sealed classes like Loading | Loaded | Error with exhaustive switch.

Which approach for which app

Situation Approach
Prototype, small app, a handful of models Hand-written models (or generated once with the converter)
Many models, a team, an API that keeps changing json_serializable
Models are also app state; you need copyWith, equality, unions freezed + json_serializable

You can mix them. Starting with hand-written models and moving to json_serializable later is a mechanical change, because the public API (fromJson and toJson) stays the same. Code generation is still the standard way to do this in Dart: the macros experiment that promised @JsonCodable without build_runner was stopped by the Dart team in early 2025.

What I use: in my own client apps I write plain fromJson/toJson by hand. It keeps the models readable and adds no code generation step to the build. I then check each model against the official Flutter and Dart documentation, and use AI tools as a second reviewer to catch a missed null case or wrong cast.

Common errors and what they mean

These are the exact messages from the Dart VM (which is what runs your app on Android and iOS), reproduced with the code next to each one.

type 'int' is not a subtype of type 'double' in type cast
You cast a whole number to double: json['price'] as double with "price": 450. Fix: (json['price'] as num).toDouble(). Without the as (for example final double price = json['price'];) the message is the same minus "in type cast".

type 'Null' is not a subtype of type 'String' in type cast
A field you declared non-nullable was null or missing. Check the raw response. Either make the field nullable, give it a default with ??, or fix the backend.

type 'List<dynamic>' is not a subtype of type 'List<String>' in type cast
json['tags'] as List<String>. A decoded JSON list is always List<dynamic>, even if every element is a string. Fix: (json['tags'] as List<dynamic>).map((e) => e as String).toList().

type '_Map<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast
You expected an array at the top level, but the API wraps it: {"data": [...]}. Cast to Map<String, dynamic> first and read the list from map['data']. _Map is just the private class jsonDecode uses for objects.

type '_Map<String, dynamic>' is not a subtype of type 'Map<String, String>' in type cast
Same root cause as the list case: decoded maps are always Map<String, dynamic>. Cast to that and convert the values, or better, write a class for the nested object.

type 'String' is not a subtype of type 'int' in type cast
The API sent "id": "42". Fix the backend if you can; otherwise use a helper like readInt above.

type 'String' is not a subtype of type 'int' of 'index'
You indexed a list with a string key: list['id'] where list is the decoded array. Take an element first (list[0]['id']), or map the list into models.

FormatException: Unexpected character (at character 1)
The body isn't JSON at all. Most often it's an HTML error page from a proxy, a login redirect, or a 500. Check the status code before calling jsonDecode. An empty body gives FormatException: Unexpected end of input (at character 1).

Summary

  • Decode once with jsonDecode, convert to typed models right away, and keep dynamic out of your widgets.
  • Read doubles through num. Decide per field what's required, optional or defaulted.
  • Map lists element by element; cast nested objects to Map<String, dynamic>.
  • Move to json_serializable when the models multiply, and add freezed when they become app state.

If you want the boilerplate done for you, paste your API response into the free JSON to Dart model converter. It handles nullable fields, int/double, ISO dates as DateTime, snake_case keys and nested lists, and outputs plain Dart, json_serializable or freezed. And if you're building a Flutter app and want someone to build it with you, tell me about your project.


Originally published at neemii.dev. I'm Muhammad Naeem, a Flutter developer with 10+ apps on the App Store and Google Play. More free tools for Flutter developers: neemii.dev/tools.

Top comments (0)