Flutter

How to convert dart object in json string in flutter?

In mobile application development, when we use rest APIs, we have to deal with json. Sometimes we need to send json to server by using rest APIs. And sometimes we have to fetch data from server in json format and convert this data into model class objects. In this tutorial we will learn how to convert dart object in json string in flutter.

Convert dart object in to json string in flutter

In Flutter, you can convert a Dart object to a JSON string using the json package, which is included in the Flutter SDK by default. Here’s a step-by-step guide on how to do it:

1- Import the dart:convert library, which includes the necessary classes for JSON encoding and decoding:

import 'dart:convert';

2- Define your Dart object. For example, let’s say you have a class called Person:

class Person {
  String name;
  int age;

  Person(this.name, this.age);
}

3- Create an instance of your Person class:

Person person = Person("John Doe", 25);

4- Use the jsonEncode() function from the json package to convert the object to a JSON string:

String jsonString = jsonEncode(person);

jsonEncode() function is a convenience function provided by the dart:convert library. It is used to convert a Dart object to its equivalent JSON representation in the form of a JSON string. It takes an argument of type Object?, which represents the Dart object you want to convert to JSON.

5- Now, jsonString will contain the JSON representation of your Person object.

Here’s the complete example:

class Person {
  String name;
  int age;

  Person(this.name, this.age);
}

void main() {
  Person person = Person("John Doe", 25);
  String jsonString = jsonEncode(person);
  print(jsonString);
}

When you run this code, it will output the following JSON string:

{"name":"John Doe","age":25}

That’s how you can convert a Dart object to a JSON string in Flutter using the json package.

Also read how to convert json string in to dart object in flutter.

Conclusion

In Flutter, we can convert a Dart object to a JSON string using the json package. By following the steps provided, we can import the necessary libraries. Then define our Dart object, create an instance of the object, and use the jsonEncode() function to convert it to a JSON string. This allows you to easily serialize your Dart objects into JSON format for various purposes such as sending data over a network or storing it in a file.

Leave a Reply

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