Sub topic 4
Turning JSON into Dart models
This chapter assumes you can already send a GET request with the http package and read response.body. It also assumes you know Dart null safety, named parameters and factory constructors. Here you will convert the JSON text in a response body into typed Dart objects, and handle the cases where the JSON doesn't match what you expected.
Why not keep the Map?
jsonDecode from dart:convert turns a JSON string into plain Dart values. The result has static type dynamic. At runtime it is a combination of these types:
| JSON value | Dart value |
|---|---|
| object | `Map<String, dynamic>` |
| array | `List<dynamic>` |
| string | `String` |
| number | `int` or `double` |
| true / false | `bool` |
| null | `null` |
You could read decoded['title'] everywhere in your UI. That has three problems. The compiler can't check key names, so a typo only fails at runtime. Every call site has to repeat the casts. And a change in the API shape forces you to hunt through the whole app.
A model class moves all of that into one place. The conversion happens once, at the boundary between the network and your code. Everything after it works with typed fields.
The basic model
The Post model from the previous chapter has the standard shape: final fields, a fromJson factory and a toJson method.
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) =>
Post(id: json['id'] as int, title: json['title'] as String);
final int id;
final String title;
Map<String, dynamic> toJson() => {'id': id, 'title': title};
}The as int and as String casts do the real work. json['id'] has type dynamic, so without a cast the compiler would accept almost anything. With the cast, a wrong value fails inside fromJson instead of surfacing later in a widget.
Two details cause most beginner bugs:
- Reading a key that does not exist returns
null, not an error.json['title'] as Stringthen throws aTypeError, becauseNullis not aString. jsonDecodereturnsObject?-like dynamic data. You must cast it toMap<String, dynamic>before callingfromJson.
Nested objects, lists, dates and numbers
Real APIs return richer data. The model below covers the cases you will meet most often. These are an optional field, a nested object, a list, a date and a number.
import 'dart:convert';
class Author {
const Author({required this.id, required this.name});
factory Author.fromJson(Map<String, dynamic> json) =>
Author(id: json['id'] as int, name: json['name'] as String);
final int id;
final String name;
Map<String, dynamic> toJson() => {'id': id, 'name': name};
}
class Article {
const Article({
required this.id,
required this.title,
required this.author,
required this.tags,
required this.rating,
this.subtitle,
this.publishedAt,
});
factory Article.fromJson(Map<String, dynamic> json) {
final published = json['published_at'] as String?;
return Article(
id: json['id'] as int,
title: json['title'] as String,
subtitle: json['subtitle'] as String?,
author: Author.fromJson(json['author'] as Map<String, dynamic>),
tags: (json['tags'] as List<dynamic>).map((t) => t as String).toList(),
rating: (json['rating'] as num).toDouble(),
publishedAt: published == null ? null : DateTime.parse(published),
);
}
final int id;
final String title;
final String? subtitle;
final Author author;
final List<String> tags;
final double rating;
final DateTime? publishedAt;
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
if (subtitle != null) 'subtitle': subtitle,
'author': author.toJson(),
'tags': tags,
'rating': rating,
if (publishedAt != null)
'published_at': publishedAt!.toIso8601String(),
};
}
void main() {
const body = '''
{
"id": 7,
"title": "Models",
"subtitle": null,
"author": {"id": 2, "name": "Ada"},
"tags": ["dart", "json"],
"rating": 5,
"published_at": "2026-11-28T10:00:00Z"
}
''';
final article = Article.fromJson(jsonDecode(body) as Map<String, dynamic>);
print('${article.title} by ${article.author.name}, '
'rating ${article.rating}, tags ${article.tags}');
print(jsonEncode(article.toJson()));
}Each field uses a different technique:
- Optional fields. Cast to a nullable type,
as String?. This accepts both a missing key and an explicitnull. If you declare the fieldStringand the server omits it, parsing fails. - Nested objects. Cast the inner value to
Map<String, dynamic>and pass it to that class's ownfromJson. Each class only knows about its own level. - Lists. A decoded array is a
List<dynamic>, even when every element is a string. Writingas List<String>throws at runtime. Map each element through a cast and calltoList(). - Numbers. The sample sends
"rating": 5.jsonDecodereturns anintfor it, soas doublewould throw. Cast tonumand calltoDouble(). - Dates. JSON has no date type, so dates arrive as strings.
DateTime.parsereads ISO 8601 text. If your API sends Unix timestamps, useDateTime.fromMillisecondsSinceEpochinstead. - Key names. APIs often use
snake_casewhile Dart fields usecamelCase. The mapping lives infromJsonandtoJson, so the rest of the app never sees the API's naming.
Decoding a list response
Many endpoints return an array at the top level. Cast the decoded value to List<dynamic> and map each element through fromJson.
import 'dart:convert';
List<Post> parsePosts(String body) {
final list = jsonDecode(body) as List<dynamic>;
return list
.map((item) => Post.fromJson(item as Map<String, dynamic>))
.toList();
}Note the second cast on each item. Elements of a List<dynamic> are dynamic, so fromJson would not accept them directly. Reuse the Post class from earlier in this chapter.
Making failures easy to diagnose
A bare TypeError such as type 'Null' is not a subtype of type 'String' in type cast does not say which field was wrong. For an API you do not control, a small helper gives a better message.
T field<T>(Map<String, dynamic> json, String key) {
final value = json[key];
if (value is T) return value;
throw FormatException(
'Field "$key" expected $T but got ${value.runtimeType}',
);
}Call it as field<int>(json, 'id') or field<String?>(json, 'subtitle'). The nullable type argument accepts null, so optional fields still work.
Dart 3 pattern matching offers another way to check shape and extract values in one step:
class Tag {
const Tag({required this.id, required this.label});
factory Tag.fromJson(Object? json) {
if (json case {'id': int id, 'label': String label}) {
return Tag(id: id, label: label);
}
throw FormatException('Unexpected tag shape: $json');
}
final int id;
final String label;
}The case pattern succeeds only when the value is a map with an int under id and a String under label. Extra keys are ignored. Otherwise control falls through to the throw.
Which exception reaches you depends on where the data went wrong:
| Problem | What is thrown |
|---|---|
| Body is not valid JSON, such as an HTML error page | `FormatException` from `jsonDecode` |
| Wrong top-level type, missing key, wrong field type | `TypeError` from a cast |
| Bad date string | `FormatException` from `DateTime.parse` |
| Your own checks, as in `field` | `FormatException` |
Catch these at the API layer and convert them to one exception type, which a later chapter builds. The UI should not need to know about TypeError.
Hand-written models or code generation
Writing fromJson by hand is fine for a handful of small models. For many models or large payloads, it becomes repetitive and easy to get wrong. The json_serializable package, together with json_annotation and build_runner, generates fromJson and toJson from annotations on your class.
| Factor | Hand-written | `json_serializable` |
|---|---|---|
| Setup | None | Extra dev dependencies and a build step |
| Typos in key names | Possible, found at runtime | Generated from field names or annotations |
| Custom logic such as odd date formats | Direct | Needs converters or annotations |
| Readability for newcomers | Every step visible | Generated file hides the details |
Start by hand so you understand what generation produces. Move to code generation once the models multiply.
Common mistakes
- Writing
as List<String>on a decoded array. The runtime type isList<dynamic>, so the cast fails. - Casting a number with
as double. Whole numbers decode asint. Useas num. - Parsing the body inside widgets. Parse once in the API function, as
fetchPostdoes, and pass models to the UI. - Making every field nullable to avoid errors. This moves the failure to every place that reads the field. Make a field nullable only when the API can really omit it.
Exercise
An API returns {"id": 3, "price": 10, "discount": null, "colors": ["red", "blue"]}. Write a Product.fromJson that gives int id, double price, double? discount and List<String> colors. Which line would fail if you wrote json['price'] as double, and why?
Show answer
Use id: json['id'] as int, price: (json['price'] as num).toDouble(), discount: (json['discount'] as num?)?.toDouble() and colors: (json['colors'] as List<dynamic>).map((c) => c as String).toList(). The price line would fail with as double because the JSON value 10 has no decimal point, so jsonDecode produces an int, and an int is not a double at runtime. Casting to num accepts both.
Exercise
A server returns an HTML error page with status 200 instead of JSON. Which exception does jsonDecode throw, and why is it better to catch it in the API layer than in a widget?
Show answer
It throws a FormatException because the text is not valid JSON. Catching it in the API layer lets you convert it to your app's single exception type once, so every widget handles one kind of failure and none depends on dart:convert details.