Sitemap

Member-only story

JSON conversion in Flutter and Dart

5 min readFeb 12, 2019

--

A quick reference with examples

Press enter or click to view image in full size

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

--

--

Suragch
Suragch

Written by Suragch

Flutter and Dart developer. Twitter: @suragch1, Email: suragch@suragch.dev