tezvyn:

JSON in Dart: Using `dart:convert`

AI-drafted, machine-checkedSource: dart.devbeginner

`dart:convert` is Dart's built-in translator for JSON. It turns Dart Maps into JSON strings (`jsonEncode`) for APIs and file storage, and parses JSON strings back into Maps (`jsonDecode`). The footgun: `jsonDecode` returns a generic Map, not your custom class.

WHY IT EXISTS: Modern apps constantly communicate with servers and store structured data. JSON is the universal text-based language for that data exchange. Dart needs a native way to "speak" JSON, allowing it to encode its own data structures into JSON and decode incoming JSON into structures it understands.

THE MENTAL MODEL: Think of dart:convert as a bilingual translator for your app. It translates between Dart's native objects (like Map and List) and the universal JSON string format. jsonEncode is the "Dart-to-JSON" function, and jsonDecode is the "JSON-to-Dart" function.

HOW IT WORKS: The library provides two core functions. First, jsonEncode(object) takes a Dart object (usually a Map<String, dynamic> or List) and returns its JSON string representation. To encode a custom class, you must first provide a toJson() method on your class that converts it to a Map. Second, jsonDecode(source) takes a JSON string and parses it into a Dart object. This typically results in a Map<String, dynamic> for JSON objects or a List<dynamic> for JSON arrays.

WHEN TO USE IT: dart:convert is perfect for simple use cases: small projects, quick API calls, or when you want to avoid adding external dependencies. Since it's part of the core Dart SDK, it's always available without any setup.

WHEN NOT TO USE IT: For applications with many complex data models, writing and maintaining manual toJson and fromJson methods is tedious and error-prone. In these scenarios, use a code-generation library like json_serializable. It automatically writes the boilerplate conversion code for you, reducing bugs and saving time.

ONE CANONICAL EXAMPLE: Imagine you fetch user data as a JSON string: String userJson = '{"id": 1, "name": "Alex"}';. To use this in Dart, you first decode it: Map<String, dynamic> userMap = jsonDecode(userJson);. This gives you a map, not a User object. You would access the name with userMap['name']. To convert this map into a typed User object, you would typically define a factory constructor on your class, like factory User.fromJson(Map<String, dynamic> json).

Read the original → dart.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.