Flutter

How to convert json string in to dart object in flutter?

When we work with json in software development, we have to convert json string in to the object. In this lessen we will learn how to convert json string into dart object in flutter.

In Flutter, json.decode is a function provided by the dart:convert library that is used to convert a JSON-encoded string into a Dart object. It deserializes the JSON string and creates a corresponding Dart object based on the structure of the JSON data.
Here’s an example of how to use json.decode:

Usage of json.decode in flutter

import 'dart:convert';

void main() {
  final jsonString = '{"name":"John Doe","age":30}';

  final data = json.decode(jsonString);
  print(data['name']); // John Doe
  print(data['age']); // 30
}

Explanation

In the example above, a JSON-encoded string jsonString is defined, representing a person’s name and age. The json.decode function is then used to convert the JSON string into a Dart object. The resulting object, data, is a Map that contains the key-value pairs from the JSON string.

You can access the values in the data object using the corresponding keys, just like you would with any other Map object in Dart.

json.decode is commonly used when working with APIs that return JSON responses. It allows us to convert the JSON response into a structured Dart object. That you can manipulate and use within your Flutter application.

It’s worth noting that the dart:convert library provides other functions and classes for working with JSON data, including json.encode for encoding Dart objects into JSON strings and json.decode for decoding JSON strings into Dart objects. These functions are fundamental for handling JSON data in Flutter applications.

Leave a Reply

Your email address will not be published. Required fields are marked *