How to encode/decode JSON in Flutter

Last updated on October 30, 2020 A Goodman Loading... Post a comment

This article shows you how to encode/decode JSON in Flutter.

1. Import the dart:convert library:

import 'dart:convert';

2. Use:

  • json.encode() or jsonEncode() for encoding
  • json.decode() or jsonDecode() for decoding

Examples

Example 1: JSON Encoding

final products = [
    {
      'id': 1,
      'name': 'Product #1'
    },
    {
      'id': 2,
      'name': 'Product #2'
    }
];
  
print(json.encode(products)); 

Output:

[{"id":1,"name":"Product #1"},{"id":2,"name":"Product #2"}]

Example 2: JSON decoding

final String responseData = '[{"id":1,"name":"Product #1"},{"id":2,"name":"Product #2"}]';
  
final products = json.decode(responseData);
  
// Print the name of the second product in the list
print(products[1]['name']);

Output:

Product #2

Hope this helps 🙂

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x