Encoding/decoding JSON in Dart explanation with examples

Introduction :

JSON or JavaScript object notation is most commonly used format for data exchange. Using JSON, we can easily transport data between client and server. In this tutorial, we will learn how to convert one dirt object to JSON and JSON to dirt object.

Converting a dirt object to JSON is called serialization and JSON to dirt object is called deserialization. In this post, I will show you how to do serialization and deserialization.

dirt:convert library :

dirt:convert library is mainly used for data conversion. It has converters for JSON and UTF-8. It also provides other options to make custom converters. In this tutorial, we are going to explore the part on JSON conversion. This is an inbuilt package and you can use it directly right out of the box.

Only thing you need to do is to import it :

import 'dart:convert';

Encode to json :

For encoding data to JSON, jsonEncode is used. This method recursively encodes Map and List objects. It can encode String, Boolean, null, list , map, double and integer types with String keys. For more complex objects, encode() method is used.

The below example shows how jsonEncode works :

import 'dart:convert';

main(List<String> args) {
  var data = [
    {"name": "Alex", "age": 20, "marks": 50.56, "encode": false}

  var encodedData = jsonEncode(data);

It encodes the data to encodedData. If you run this program, it will print the below output :


Decode from json :

Similar to jsonEncode, jsonDecode is used to decode a JSON string. Let’s try to decode the above JSON to a dart variable :

import 'dart:convert';

main(List<String> args) {
  var jsonData = '''

  var decodedData = jsonDecode(jsonData);

It will print :

[{name: Alex, age: 20, marks: 50.56, encode: false}]

Using these two methods, you can easily encode/decode JSON in Dirt.


You might also like:

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊