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:
- Add the
json_serializable
package to yourpubspec.yaml
file:
dependencies:
json_annotation: ^4.4.0
json_serializable: ^4.1.4
Run
flutter pub get
to fetch the package.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';
@JsonSerializable()
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);
}
- 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.
- Now you can use the generated serialization methods. To convert a JSON string to an instance of the
User
class, useUser.fromJson(json)
. To convert an instance of theUser
class to a JSON string, useuser.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.