0
0
Fluttermobile~5 mins

JSON parsing (jsonDecode) in Flutter

Choose your learning style9 modes available
Introduction

We use JSON parsing to turn text data into objects our app can understand and use.

When you get data from the internet in JSON format.
When you read a JSON file stored on the device.
When you want to convert a JSON string into Dart objects to show in the app.
Syntax
Flutter
import 'dart:convert';

var data = jsonDecode(jsonString);

jsonDecode converts a JSON string into Dart objects like Map or List.

Make sure to import 'dart:convert' to use jsonDecode.

Examples
This converts a JSON string representing a user into a Map object.
Flutter
import 'dart:convert';

var jsonString = '{"name":"Alice","age":30}';
var user = jsonDecode(jsonString);
This converts a JSON array string into a Dart List.
Flutter
import 'dart:convert';

var jsonString = '[1, 2, 3]';
var numbers = jsonDecode(jsonString);
Sample App

This app parses a JSON string and shows the title in the app bar and the count in the center.

Flutter
import 'dart:convert';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    const jsonString = '{"title":"Hello Flutter","count":5}';
    final Map<String, dynamic> data = jsonDecode(jsonString);

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text(data['title'])),
        body: Center(
          child: Text('Count is: ${data['count']}'),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

jsonDecode throws an error if the JSON string is invalid, so handle exceptions if needed.

The result of jsonDecode is usually a Map for JSON objects or a List for JSON arrays.

Summary

jsonDecode converts JSON text into Dart objects.

Use it to read data from APIs or files in JSON format.

Remember to import 'dart:convert' before using jsonDecode.