JSON with dart:convert
JSON is the lingua franca of web APIs and config files. Dart's built-in dart:convert library converts between JSON text and Dart objects:
jsonDecode(String)→dynamic(maps becomeMap<String, dynamic>, arrays becomeList<dynamic>)jsonEncode(Object?)→String
Decoding and encoding
import 'dart:convert';
void main() {
const text = '{"id": 7, "name": "Lotus Tea", "price": 3.5, "tags": ["hot", "organic"], "stock": null}';
final data = jsonDecode(text) as Map<String, dynamic>;
print(data['name']);
print(data['tags']);
print(data['price'].runtimeType);
print(data['stock']);
final back = jsonEncode({'ok': true, 'count': 2, 'items': [1, 2]});
print(back);
const pretty = JsonEncoder.withIndent(' ');
print(pretty.convert({'user': 'Lam', 'roles': ['admin']}));
}Lotus Tea
[hot, organic]
double
null
{"ok":true,"count":2,"items":[1,2]}
{
"user": "Lam",
"roles": [
"admin"
]
}
| JSON | Dart |
|---|---|
object {} |
Map<String, dynamic> |
array [] |
List<dynamic> |
| string | String |
| number | int (no decimal point) or double |
true / false |
bool |
null |
null |
From maps to typed classes
Working with Map<String, dynamic> everywhere loses type safety. The standard approach: a model class with a fromJson factory and a toJson method. Convert at the edge of your program; use typed objects everywhere else.
import 'dart:convert';
class Product {
final int id;
final String name;
final double price;
final List<String> tags;
const Product({required this.id, required this.name, required this.price, this.tags = const []});
factory Product.fromJson(Map<String, dynamic> json) => Product(
id: json['id'] as int,
name: json['name'] as String,
price: (json['price'] as num).toDouble(), // 5 or 5.0 are both fine
tags: (json['tags'] as List<dynamic>? ?? []).cast<String>(),
);
Map<String, dynamic> toJson() => {'id': id, 'name': name, 'price': price, 'tags': tags};
@override
String toString() => 'Product($id, $name, $price, $tags)';
}
void main() {
const body = '[{"id": 1, "name": "Pen", "price": 2, "tags": ["office"]}, {"id": 2, "name": "Mug", "price": 6.5}]';
final products = (jsonDecode(body) as List<dynamic>)
.map((e) => Product.fromJson(e as Map<String, dynamic>))
.toList();
products.forEach(print);
print(jsonEncode(products)); // calls toJson() on each object
}Product(1, Pen, 2.0, [office])
Product(2, Mug, 6.5, [])
[{"id":1,"name":"Pen","price":2.0,"tags":["office"]},{"id":2,"name":"Mug","price":6.5,"tags":[]}]
jsonEncode automatically calls a toJson() method on objects it doesn't know how to encode.
Parsing with patterns
Dart 3 patterns make validation part of decoding — the case either matches the exact shape you expect or falls through to an error:
import 'dart:convert';
typedef User = ({String name, int age, String? email});
User parseUser(String text) {
final json = jsonDecode(text);
if (json case {'name': String name, 'age': int age}) {
final email = json['email'];
return (name: name, age: age, email: email is String ? email : null);
}
throw FormatException('Invalid user JSON', text);
}
void main() {
print(parseUser('{"name": "Hoang", "age": 41, "email": "h@x.vn"}'));
print(parseUser('{"name": "Yen", "age": 19}'));
try {
parseUser('{"name": "Bad", "age": "nineteen"}');
} on FormatException catch (e) {
print('${e.message}: ${e.source}');
}
}(age: 41, email: h@x.vn, name: Hoang)
(age: 19, email: null, name: Yen)
Invalid user JSON: {"name": "Bad", "age": "nineteen"}
Handling malformed JSON
Invalid text throws a FormatException:
import 'dart:convert';
Object? tryDecode(String text) {
try {
return jsonDecode(text);
} on FormatException catch (e) {
print('bad JSON: ${e.message}');
return null;
}
}
void main() {
print(tryDecode('{"a": 1}'));
print(tryDecode("{'a': 1}")); // single quotes aren't valid JSON
}{a: 1}
bad JSON: Unexpected character
null
Other codecs in dart:convert
| Codec | Converts |
|---|---|
json |
Objects ↔ JSON text |
utf8 |
String ↔ bytes (List<int>) |
base64 / base64Url |
Bytes ↔ Base64 text |
latin1, ascii |
Legacy encodings |
LineSplitter |
Text → lines |
final bytes = utf8.encode('Xin chào'); // [88, 105, 110, 32, 99, 104, 195, 160, 111]
final token = base64.encode(bytes); // WGluIGNow6Bv
final text = utf8.decode(base64.decode(token));Tip: For larger models, code generators such as
json_serializableorfreezedwritefromJson/toJsonfor you. Understanding the hand-written version first makes the generated code much less mysterious.
Test yourself
What is the static return type of jsonDecode?
- Map<String, dynamic>
- dynamic
- Object
- String
Why write (json['price'] as num).toDouble() instead of json['price'] as double?
- It's faster
- JSON numbers without a decimal point decode as int, so
as doublewould fail for 5 - double can't be cast
- To round the value
How does jsonEncode serialise an instance of your own class?
- It can't
- It calls the object's
toJson()method - It uses reflection on all fields
- It calls toString()