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 dart object to JSON and JSON to dart object.

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

dart:convert library :

dart: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);
  print(encodedData);
}

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

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

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 = '''
  [{"name":"Alex","age":20,"marks":50.56,"encode":false}]
  ''';

  var decodedData = jsonDecode(jsonData);
  print(decodedData);
}

It will print :

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

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

https://dart.dev/guides/libraries/library-tour#dartconvert---decoding-and-encoding-json-utf-8-and-more

You might also like: