Convert Object To Json In Dart & Flutter
In this article, we will explore the Convert Object To Json In Dart & Flutter. We see how to execute a demo program. We will tell you the two ways to Convert objects to Json in your Dart & Flutter applications.
If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.
Table Of Contents::
Using json_serializable package
Using without package
This approach includes physically composing functions to convert your Dart object to and from JSON. Here you have full command over the serialization cycle.
Steps:
- Define your class.
- Create a method inside the class to convert the object into a
Map
. - Convert the
Map
object to a JSON string using thejsonEncode()
function from thedart:convert
library.
import 'dart:convert';
import 'package:flutter/foundation.dart' show debugPrint;
class User {
final String name;
final int age;
final bool isAdult
User(this.name, this.age, this.isAdult);
Map<String, dynamic> toJson() {
return {
'name': name,
'age': age,
"isAdult": isAdult,
};
}
}
void main() {
User user = User('Ray Thomas', 28, true);
String jsonString = jsonEncode(user.toJson());
debugPrint(json String);
}
When we run the application, we ought to get the screen’s output like the underneath screen Console Output.
{"name":"Ray Thomas","age":28,"isAdult":true}
This method is adaptable and requires no outer dependencies or packages. The tradeoff is that you need to think of some additional code and the rationale might change on various use cases. As the intricacy of your objects increases, the manual execution can become error-prone and inefficient.
Using json_serializable package
This arrangement involves the json_serializable package that gives code age to JSON serialization and deserialization. In the accompanying model, we’ll characterize a Client class that is more confounded than the one you’ve found in the preceding example. This time, we’ll place the class in a different document named user. dart.
Steps:
- Install the
json_annotation
,json_serializable
, andbuild_runner
packages by executing this command.
flutter pub add json_annotation json_serializable build_runner
Then run this one:
flutter pub get
- In the
lib
directory of your Flutter project, add a new file calleduser.dart
. Define theUser
class with the@JsonSerializable()
annotation like so:
// lib/user.dart
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
String name;
int age;
@JsonKey(name: 'is_author')
bool isAuthor;
User(this.name, this.age, this.isAuthor);
Map<String, dynamic> toJson() => _$UserToJson(this);
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}
- Build the JSON serialization code with
build_runner
by performing the following command
dart run build_runner build
A new file named user.g.dart
will be automatically generated in your lib
folder:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'user.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
User _$UserFromJson(Map<String, dynamic> json) => User(
json['name'] as String,
json['age'] as int,
json['is_admin'] as bool,
);
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
'name': instance.name,
'age': instance.age,
'is_author': instance.isAthor,
};
Use the generated toJson()
method to convert the object or a list of objects to a JSON string. You can also use the generated fromJson()
method to convert a JSON string back to an object or a list of objects.
// lib/main.dart
import 'dart:convert' show jsonEncode;
import 'package:flutter/foundation.dart' show kDebugMode;
import 'user.dart';
void main() {
User user = User('Roy Thomas', 28, true);
Map<String, dynamic> jsonUser = user.toJson();
if (kDebugMode) {
print(jsonEncode(jsonUser));
// Prints: {"name":"Roy Thomase","age":28,"is_author":true}
}
List<User> users = [
User('FlutterFevs.com', 33, true),
User('Sam Fand', 22, false),
User('Allen', 30, false),
];
List<Map<String, dynamic>> jsonUsers =
users.map((user) => user.toJson()).toList();
if (kDebugMode) {
print(jsonEncode(jsonUsers));
// Prints: [{"name":"FlutterFevs.com","age":33,"is_admin":true},{"name":"Sam Fand',"age":22,"is_admin":false},{"name":"Allen","age":30,"is_admin":false}]
}
}
This approach supports converting nested objects and complex types such as dates or enums to JSON strings with annotations. However, it requires adding a bunch of external dependencies and packages to your project. You’ll also have to run a command to generate the code for the toJson()
and fromJson()
methods every time you make changes to your classes.
Conclusion:
In the article, I have explained the Convert Object To Json In Dart & Fluttert; you can modify this code according to your choice. This was a small introduction to Convert Object To Json In Dart & Flutter User Interaction from my side, and it’s working using Flutter.
I hope this blog will provide you with sufficient information on Trying the Convert Object To Json In Dart & Flutter of your projects. We’ve examined two different ways to turn a class object into JSON. The first one is quick and works well for simple use cases. The second one is powerful and shines with complex data structures. So please try it.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.