Question #141MediumGeneral

How to convert Map to string and string to Map ?

Answer

Overview

Converting between

text
Map
and
text
String
in Dart is done using
text
dart:convert
's
text
jsonEncode
/
text
jsonDecode
for JSON, or
text
toString()
for debugging.


Map to String

Method 1: jsonEncode (JSON format — Recommended)

dart
import 'dart:convert';

final map = {'name': 'Alice', 'age': 28, 'active': true};

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

Method 2: toString() (Dart debug format)

dart
final map = {'name': 'Alice', 'age': 28};
final str = map.toString();
print(str); // {name: Alice, age: 28}  ← Dart format (NOT valid JSON)

Method 3: Custom Serialization

dart
final map = {'key1': 'val1', 'key2': 'val2'};
// Build custom string
String result = map.entries
    .map((e) => '${e.key}=${e.value}')
    .join('&');
print(result); // key1=val1&key2=val2  (query string format)

String to Map

Method 1: jsonDecode (JSON String → Map)

dart
import 'dart:convert';

final jsonStr = '{"name":"Alice","age":28,"active":true}';

// JSON String → Map<String, dynamic>
final Map<String, dynamic> map = jsonDecode(jsonStr);
print(map['name']);   // Alice
print(map['age']);    // 28
print(map['active']); // true

Method 2: Parse Custom String Format

dart
// Query string format: "key1=val1&key2=val2"
String queryString = 'name=Alice&age=28&city=Chennai';

final map = Map.fromEntries(
  queryString.split('&').map((kv) {
    final parts = kv.split('=');
    return MapEntry(parts[0], parts[1]);
  }),
);
print(map); // {name: Alice, age: 28, city: Chennai}

With Nested Maps

dart
// Nested Map → JSON String
final nested = {
  'user': {'name': 'Bob', 'scores': [100, 95, 88]},
  'active': true
};
final json = jsonEncode(nested);
// {"user":{"name":"Bob","scores":[100,95,88]},"active":true}

// JSON String → Nested Map
final decoded = jsonDecode(json) as Map<String, dynamic>;
final user = decoded['user'] as Map<String, dynamic>;
print(user['name']); // Bob

With Custom Model Classes

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

  // Model → Map
  Map<String, dynamic> toJson() => {'name': name, 'age': age};

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

// Usage
final user = User(name: 'Alice', age: 28);
final mapStr = jsonEncode(user.toJson()); // Model → String
final restored = User.fromJson(jsonDecode(mapStr)); // String → Model

Quick Reference

DirectionMethodOutput
Map → String
text
jsonEncode(map)
text
'{"key":"value"}'
String → Map
text
jsonDecode(str)
text
Map<String, dynamic>
Map → Debug string
text
map.toString()
text
{key: value}

Use

text
jsonEncode
/
text
jsonDecode
when working with APIs. Use
text
toString()
only for debugging — its output is not valid JSON.