free geoip
47

Working with JSON in Dart: Complete Beginner’s Guide

Working with JSON in Dart is essential for building modern mobile or web applications using Flutter or Dart. JSON (JavaScript…

Working with JSON in Dart is essential for building modern mobile or web applications using Flutter or Dart. JSON (JavaScript Object Notation) is a popular data format for exchanging information between servers and clients. In Dart, handling JSON is straightforward using built-in dart:convert package which provides jsonEncode and jsonDecode functions.

Working with JSON in Dart

This article will walk you through parsing JSON from a string, mapping JSON to a custom Dart class, and encoding a Dart object back into a JSON string.

1. Importing Required Library

import 'dart:convert';

2. Sample JSON Data

Here’s a simple JSON data string we want to decode:

{
  "name": "John Doe",
  "email": "john@example.com",
  "age": 28
}

3. Dart Class to Map JSON

Create a model class that mirrors the structure of the JSON.

class User {
  final String name;
  final String email;
  final int age;

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

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'],
      email: json['email'],
      age: json['age'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'email': email,
      'age': age,
    };
  }
}

4. Parsing JSON to Dart Object

void main() {
  String jsonString = '{"name":"John Doe","email":"john@example.com","age":28}';

  Map<String, dynamic> userMap = jsonDecode(jsonString);
  User user = User.fromJson(userMap);

  print('Name: ${user.name}');
  print('Email: ${user.email}');
  print('Age: ${user.age}');
}

5. Converting Dart Object to JSON String

void convertToJson() {
  User user = User(name: 'Jane Doe', email: 'jane@example.com', age: 25);
  String jsonString = jsonEncode(user.toJson());

  print(jsonString);
}

Working with JSON in Dart allows easy integration with REST APIs, data storage, and state management. For large or complex models, consider using the json_serializable package to generate model code automatically.

By understanding JSON parsing and encoding, Dart developers can confidently build data-driven applications with better structure and scalability.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *