Question #234EasyAPIs & Networking

What is the difference between json encode and json decode ?

#json

Answer

Overview

text
jsonEncode
and
text
jsonDecode
are mirror operations from
text
dart:convert
. One converts Dart objects to JSON strings; the other converts JSON strings back to Dart objects.


jsonEncode — Dart → JSON String

dart
import 'dart:convert';

// Map → JSON string
final map = {'name': 'Alice', 'age': 28, 'active': true};
final jsonString = jsonEncode(map);
print(jsonString);       // {"name":"Alice","age":28,"active":true}
print(jsonString.runtimeType); // String

// List → JSON string
final list = [1, 'two', true, null];
print(jsonEncode(list)); // [1,"two",true,null]

// Nested objects
final nested = {
  'user': {'name': 'Bob', 'scores': [100, 95, 88]},
  'active': true
};
print(jsonEncode(nested));
// {"user":{"name":"Bob","scores":[100,95,88]},"active":true}

jsonDecode — JSON String → Dart

dart
import 'dart:convert';

// JSON string → Map
final jsonStr = '{"name":"Alice","age":28}';
final decoded = jsonDecode(jsonStr);        // dynamic
final map = decoded as Map<String, dynamic>;
print(map['name']); // Alice
print(map['age']);  // 28

// JSON array string → List
final listStr = '[1, 2, 3]';
final list = jsonDecode(listStr) as List<dynamic>;
print(list); // [1, 2, 3]

With Custom Model Classes

dart
class User {
  final String name;
  final int age;
  User({required this.name, required this.age});

  // Dart object → Map (used with jsonEncode)
  Map<String, dynamic> toJson() => {'name': name, 'age': age};

  // Map (from jsonDecode) → Dart object
  factory User.fromJson(Map<String, dynamic> json) =>
      User(name: json['name'], age: json['age']);
}

void main() {
  final user = User(name: 'Alice', age: 28);

  // Encode: User → JSON string
  final encoded = jsonEncode(user.toJson()); // '{"name":"Alice","age":28}'

  // Decode: JSON string → User
  final decoded = User.fromJson(jsonDecode(encoded));
  print(decoded.name); // Alice
}

In HTTP Requests

dart
// Sending data (encode)
await http.post(
  Uri.parse('https://api.example.com/users'),
  headers: {'Content-Type': 'application/json'},
  body: jsonEncode({'name': 'Alice', 'age': 28}), // ← Dart map → JSON string
);

// Receiving data (decode)
final response = await http.get(Uri.parse('https://api.example.com/users/1'));
final user = User.fromJson(jsonDecode(response.body)); // ← JSON string → Dart map

Quick Reference

FunctionInputOutputUse When
text
jsonEncode
Dart Map/List/valueJSON
text
String
Sending to API
text
jsonDecode
JSON
text
String
Dart
text
dynamic
Receiving from API

Memory Trick:

text
jsonEncode
= pack data into a JSON string.
text
jsonDecode
= unpack data out of a JSON string.