how to make model class for complex json in flutter
To create a model class for complex JSON in Flutter, you can follow these steps:
Analyze the JSON structure: Take a close look at the JSON data you have and identify its structure, including the different fields and their types.
Generate the model class: Flutter provides a handy tool called
json_serializable
that can automatically generate model classes based on JSON data. To use it, you need to add thejson_annotation
andjson_serializable
dependencies to yourpubspec.yaml
file.
yaml
dependencies:
json_annotation: ^4.4.0
json_serializable: ^4.1.4
- Create the model class: In your Dart file, import the necessary packages and define your model class. Annotate the class with
@JsonSerializable()
to enable code generation.
```dart import 'package:json_annotation/json_annotation.dart';
part 'your_model_class.g.dart';
@JsonSerializable() class YourModelClass { // Define the fields of your model class based on the JSON structure final String field1; final int field2; // ...
YourModelClass({
required this.field1,
required this.field2,
// ...
});
// Add a factory constructor for JSON deserialization
factory YourModelClass.fromJson(Map<String, dynamic> json) =>
_$YourModelClassFromJson(json);
// Add a method for JSON serialization
Map<String, dynamic> toJson() => _$YourModelClassToJson(this);
} ```
- Generate the model class: Run the following command in your terminal to generate the necessary code for JSON serialization and deserialization:
flutter pub run build_runner build
This command will generate the file your_model_class.g.dart
that contains the necessary code for JSON serialization and deserialization.
- Use the model class: Now you can use your model class to parse JSON data. For example, if you have a JSON string, you can parse it like this:
dart
String jsonString = '{"field1": "value1", "field2": 42}';
Map<String, dynamic> json = jsonDecode(jsonString);
YourModelClass model = YourModelClass.fromJson(json);
You can access the fields of the model class like any other Dart object:
dart
print(model.field1); // Output: value1
print(model.field2); // Output: 42
That's it! You now have a model class that can handle complex JSON data in Flutter. Remember to adjust the field types and names according to your JSON structure.