7 C
New York
Friday, December 8, 2023

How to encode/decode JSON in Flutter

A Quick Note

This article shows you how to encode/decode JSON in Flutter. The steps you need to follow are:

1. Import the dart:convert library:Advertisements

import 'dart:convert';

2. Use:

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

Examples

Example 1: JSON Encoding

import 'dart:convert';

void main() {
  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

import 'dart:convert';
import 'package:flutter/foundation.dart';

void main() {
  const String responseData =
      '[{"id":1,"name":"Product #1"},{"id":2,"name":"Product #2"}]';

  final products = json.decode(responseData);

  if (kDebugMode) {
    // Print the type of "products"
    print(products.runtimeType);

    // Print the name of the second product in the list
    print(products[1]['name']);
  }
}

Output:

List<dynamic>
Product #2

Hope this helps. Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Advertisements

Related Articles

Latest Articles