Flutter Course – 15.6 JSON Data

In recent mobile app development, the JSON (JavaScript Object Notation) data format is widely used for data transmission and storage. JSON data has a structurally simple form, is highly readable compared to other data formats, and can be easily parsed in most programming languages.

1. Definition and Characteristics of JSON

JSON is a lightweight data interchange format that is easily readable and writable by both humans and machines. While JSON is based on the syntax of JavaScript object literals, it is also very useful for data interchange between different languages. The main characteristics of JSON are as follows:

  • Lightweight: It has a simple structure, resulting in low overhead for data transmission.
  • Readability: It is in a format that is easy for humans to read.
  • Flexibility: It can represent complex data structures.

2. JSON Format

JSON data is expressed in key-value pairs. Here is an example of a JSON object:

{
    "name": "John Doe",
    "age": 30,
    "isDeveloper": true,
    "skills": ["Dart", "Flutter", "JavaScript"],
    "address": {
        "city": "Seoul",
        "postalCode": "12345"
    }
}

3. Using JSON Data in Flutter

To utilize JSON data in Flutter, you can either fetch data from an external API through HTTP requests or read data from a local JSON file. This section outlines the basic procedures for using JSON data through both methods.

3.1. Fetching JSON Data via HTTP Requests

You can use the HTTP package in Flutter to fetch JSON data from an API.

Here is an example of code that retrieves JSON data from an API:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future fetchData() async {
    final response = await http.get(Uri.parse('https://api.example.com/data'));

    if (response.statusCode == 200) {
        // Data successfully returned from the server
        var jsonData = json.decode(response.body);
        print(jsonData);
    } else {
        throw Exception('Error occurred while loading data');
    }
}

3.2. Reading Data from a Local JSON File

In some cases, you can read data from a built-in JSON file in the app. You can load a JSON file using the following steps.

Step 1: Add the JSON file to the app’s assets folder.

Step 2: Add the assets to the pubspec.yaml file.

flutter:
    assets:
        - assets/data.json

Step 3: Write code to read the JSON file:

import 'dart:convert';
import 'package:flutter/services.dart' as rootBundle;

Future loadJsonData() async {
    final jsonData = await rootBundle.rootBundle.loadString('assets/data.json');
    final data = json.decode(jsonData);
    print(data);
}

4. Connecting JSON Data to Model Classes

To utilize JSON data in a Flutter app, it is common to convert the data into model classes. Here is an example of how to convert JSON data into a model class.

class User {
    String name;
    int age;
    bool isDeveloper;
    List skills;

    User({required this.name, required this.age, required this.isDeveloper, required this.skills});

    factory User.fromJson(Map json) {
        return User(
            name: json['name'],
            age: json['age'],
            isDeveloper: json['isDeveloper'],
            skills: List.from(json['skills']),
        );
    }
}

Using the class, you can easily convert JSON data into objects for use.

5. Displaying JSON Data in Flutter Widgets

Once the JSON data is fetched, let’s explore how to display that data in Flutter widgets. For example, we can create a widget that displays the user information on the screen.

class UserProfile extends StatelessWidget {
    final User user;

    UserProfile({required this.user});

    @override
    Widget build(BuildContext context) {
        return Column(
            children: [
                Text('Name: ${user.name}'),
                Text('Age: ${user.age}'),
                Text('Is Developer: ${user.isDeveloper ? "Yes" : "No"}'),
                Text('Skills: ${user.skills.join(', ')}'),
            ],
        );
    }
}

6. Exception Handling and Error Management

Handling errors that may occur during JSON data operations is very important. Let’s look at how to handle exceptions that may arise during HTTP requests or JSON parsing.

Future fetchData() async {
    try {
        final response = await http.get(Uri.parse('https://api.example.com/data'));
        if (response.statusCode == 200) {
            // Successfully fetched JSON data
            var jsonData = json.decode(response.body);
            print(jsonData);
        } else {
            throw Exception('Server error: ${response.statusCode}');
        }
    } catch (e) {
        print('Error occurred: $e');
    }
}

7. Comparison of JSON and Other Data Formats

JSON has several advantages and disadvantages when compared to other data formats such as XML and CSV. Here is a comparison between JSON and XML:

Feature JSON XML
Readability Excellent Average
Data Size Small Large
Structure Key-Value pairs Tag-based

8. Conclusion

In this tutorial, we covered the basic methods for handling JSON data in Flutter. By using JSON, we facilitate data management and provide the flexibility to support various required data formats. Based on the experience of using JSON data in practical projects, try to implement more functions.

If you need additional resources, please refer to the official Flutter documentation: Flutter Documentation.

© 2023 Flutter Course – All Rights Reserved.