flutter json serialization command

To perform JSON serialization in Flutter, you can use the built-in json_serializable package. Here are the steps to use it:

  1. Add the json_serializable package to your pubspec.yaml file:
  json_annotation: ^4.4.0
  json_serializable: ^4.1.4
  1. Run flutter pub get to fetch the package.

  2. Create a Dart class that represents your JSON data. Annotate the class with @JsonSerializable and add the necessary annotations to the class fields. For example:

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

class User {
  final String name;
  final int age;

  User(this.name, this.age);

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
  1. Run the code generation command to generate the serialization code:
flutter pub run build_runner build

This command will generate the necessary serialization code for your User class.

  1. Now you can use the generated serialization methods. To convert a JSON string to an instance of the User class, use User.fromJson(json). To convert an instance of the User class to a JSON string, use user.toJson(). For example:
String jsonString = '{"name": "John Doe", "age": 25}';
Map<String, dynamic> json = jsonDecode(jsonString);
User user = User.fromJson(json);

print(user.name); // Output: John Doe

String userJson = jsonEncode(user.toJson());
print(userJson); // Output: {"name":"John Doe","age":25}

That's it! You have successfully performed JSON serialization in Flutter using the json_serializable package.