Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart JSON


Share

Dart JSON

JSON (JavaScript Object Notation) is a text format for storing and sending data.

Apps and websites use JSON to send data to each other, for example when an app gets the weather from a server.

This is what JSON looks like:

{"name": "Anna", "age": 31, "languages": ["Dart", "Python"]}

JSON looks a lot like a Dart map and list, but it is only text, a String.

The dart:convert library has two functions to go between Dart objects and JSON:

  • jsonEncode() turns a Dart object into a JSON string.
  • jsonDecode() turns a JSON string into a Dart object.

Map to JSON

To turn a map into JSON, use jsonEncode().

The result is a normal string, so you can save it in a file or send it over the internet:

Example

import 'dart:convert';

void main() {
  Map<String, dynamic> person = {
    'name': 'Anna',
    'age': 31,
    'student': false,
    'languages': ['Dart', 'Python'],
  };
  String json = jsonEncode(person);
  print(json);
  print(json.runtimeType);
}
Try it Yourself »

Result:

{"name":"Anna","age":31,"student":false,"languages":["Dart","Python"]}
String

Notice that JSON always uses double quotes around strings.

You can encode strings, numbers, booleans, null, lists and maps with string keys.

To make the JSON easier to read, use a JsonEncoder with an indent:

Example

import 'dart:convert';

void main() {
  Map<String, dynamic> car = {'brand': 'Volvo', 'year': 2024, 'electric': true};
  JsonEncoder encoder = JsonEncoder.withIndent('  ');
  print(encoder.convert(car));
}
Try it Yourself »

Result:

{
  "brand": "Volvo",
  "year": 2024,
  "electric": true
}


JSON to Map

To read JSON, use jsonDecode().

A JSON object becomes a Map<String, dynamic>, and you can read the values with their keys:

Example

import 'dart:convert';

void main() {
  String json = '{"name": "Liam", "age": 25, "city": "Oslo"}';
  Map<String, dynamic> user = jsonDecode(json);
  print(user['name']);
  print(user['age'] + 1);
  print(user['city']);
}
Try it Yourself »

Result:

Liam
26
Oslo

The type dynamic means that the value can be of any type, because Dart cannot know the types in a JSON string before it reads it.

A JSON array becomes a Dart List:

Example

import 'dart:convert';

void main() {
  String json = '[{"fruit": "Apple", "price": 3}, {"fruit": "Banana", "price": 2}]';
  List<dynamic> items = jsonDecode(json);
  for (var item in items) {
    print('${item['fruit']} costs ${item['price']} dollars');
  }
}
Try it Yourself »

Result:

Apple costs 3 dollars
Banana costs 2 dollars

Invalid JSON

If the string is not valid JSON, jsonDecode() throws a FormatException.

Use try and catch when the JSON comes from outside your program:

Example

import 'dart:convert';

void main() {
  String json = "{'name': 'Liam'}";
  try {
    var data = jsonDecode(json);
    print(data);
  } on FormatException {
    print('This is not valid JSON');
  }
}
Try it Yourself »

Result:

This is not valid JSON

This JSON is not valid, because it uses single quotes.


Classes and JSON

In real programs, you often want to turn JSON into an object of your own class, and back again.

The common way to do this is to give the class two members:

  • A toJson() method that returns a map.
  • A factory constructor called fromJson() that creates an object from a map.

Example

import 'dart:convert';

class Book {
  final String title;
  final int pages;

  Book(this.title, this.pages);

  factory Book.fromJson(Map<String, dynamic> json) {
    return Book(json['title'] as String, json['pages'] as int);
  }

  Map<String, dynamic> toJson() {
    return {'title': title, 'pages': pages};
  }
}

void main() {
  Book book = Book.fromJson(jsonDecode('{"title": "Dune", "pages": 412}'));
  print('${book.title} has ${book.pages} pages');

  Book newBook = Book('Emma', 474);
  print(jsonEncode(newBook.toJson()));
}
Try it Yourself »

Result:

Dune has 412 pages
{"title":"Emma","pages":474}

The as String and as int parts tell Dart the type of each value, so the fields get the right type.

Tip: If an object has a toJson() method, jsonEncode() calls it for you.

So jsonEncode(newBook) gives the same result as jsonEncode(newBook.toJson()).



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.