A quick reference with examples
Article updated July 4, 2023 for Dart 3.
The article Parsing Complex JSON in Flutter is very good, but I was looking for something shorter, a quick reference with examples.
If I have a simple JSON string like this:
{
"name" : "Mary",
"age" : 30
}
How do I convert it to a Dart object? Or a Dart object to JSON?
Setup
Import the builtin convert
library, which includes the jsonDecode()
and jsonEncode()
methods:
import 'dart:convert';
I will use the class below in the following examples:
class Person {
Person(this.name, this.age);
final String name;
final int age;
}
And while it isn’t absolutely necessary, I’m also using the strict typing rules in analysis_options.yaml. This lets the analyzer warn you when you might forget about dynamic
and object types.
include: package:lints/recommended.yaml
analyzer:
language:
strict-casts: true
strict-raw-types: true
This uses the standard lints
package in pubspec.yaml:
dev_dependencies:
lints: ^2.0.0
Method 1: Direct conversion
Doing it this way is very succinct and everything is built in with the dart:convert
library. The disadvantage is that we don’t have as much type safety, and it is easy to make typos when writing the map key names.
JSON → object
String rawJson = '{"name":"Mary","age":30}';
final map = jsonDecode(rawJson);
final name = map['name'] as String;
final age = map['age'] as int;
final person = Person(name, age);
Decoded JSON doesn’t include the types. It’s dynamic
. So that’s why you needed to tell Dart the type using the as
keyword.
Object → JSON
We will use jsonEncode()
, but it only accepts numbers, Booleans, strings, nulls, lists or maps with string keys. So we have to convert our object to a map first:
final person = Person('Mary', 30);
final map = {
'name': person.name,
'age'…