Question #140EasyAPIs & Networking

What is the difference between jsonEncode vs jsonDecode ?

#json

Answer

Overview

text
jsonEncode
and
text
jsonDecode
are Dart functions from
text
dart:convert
for converting between Dart objects and JSON strings.


jsonEncode — Dart Object → JSON String

dart
import 'dart:convert';

// Map to JSON string
final user = {'name': 'Alice', 'age': 28, 'isActive': true};
final jsonString = jsonEncode(user);
print(jsonString); // {"name":"Alice","age":28,"isActive":true}

// List to JSON string
final items = [1, 'hello', true, null];
print(jsonEncode(items)); // [1,"hello",true,null]

jsonDecode — JSON String → Dart Object

dart
import 'dart:convert';

final jsonString = '{"name":"Alice","age":28,"isActive":true}';

// Returns dynamic — usually a Map or List
final Map<String, dynamic> user = jsonDecode(jsonString);
print(user['name']); // Alice
print(user['age']);  // 28

// Decoding a JSON array
final listString = '[1, 2, 3, 4]';
final List<dynamic> numbers = jsonDecode(listString);
print(numbers); // [1, 2, 3, 4]

With HTTP API Response

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

Future<User> fetchUser(int id) async {
  final response = await http.get(
    Uri.parse('https://api.example.com/users/$id'),
  );

  if (response.statusCode == 200) {
    // response.body is a String → decode it to Map
    final Map<String, dynamic> data = jsonDecode(response.body);
    return User.fromJson(data);
  }
  throw Exception('Failed to load user');
}

// Sending data — encode Dart map to JSON string
Future<void> createUser(User user) async {
  await http.post(
    Uri.parse('https://api.example.com/users'),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode(user.toJson()), // Map → JSON string for request body
  );
}

Comparison Table

Feature
text
jsonEncode
text
jsonDecode
DirectionDart → JSON StringJSON String → Dart
InputMap, List, String, num, bool, nullJSON String
Output
text
String
text
dynamic
(Map, List, etc.)
Use caseSending data to API (request body)Receiving data from API (response body)

Custom Object Serialization

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

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

  // Dart object → Map (for 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']);
}

// Full round-trip
final user = User(name: 'Alice', age: 28);
final encoded = jsonEncode(user.toJson());   // '{"name":"Alice","age":28}'
final decoded = User.fromJson(jsonDecode(encoded)); // User object

Memory Aid:

  • text
    jsonEncode
    Encode = Pack into a string (send it away)
  • text
    jsonDecode
    Decode = Unpack from a string (read it in)