While deserializing JSON is an extremely common task, there are cases where you also need to serialize some JSON. It's very important to learn how to transform a Dart class into a JSON string. Follow these steps:
- To perform this task, add a new method to the Pizza class, in the pizza.dart file, called toJson. This will actually return a Map<String, dynamic> from the object:
Map<String, dynamic> toJson() {
return {
'id': id,
'pizzaName': pizzaName,
'description': description,
'price': price,
'imageUrl': imageUrl,
};
}
- Once you have a Map, you can serialize it back into a JSON string. Add a new method at the bottom of the _MyHomePageState class, in the main.dart file, called convertToJSON:
String convertToJSON(List<Pizza> pizzas) {
String json = '[';
pizzas.forEach((pizza) {
json += jsonEncode(pizza);
});
json += ']';
return json;
}
This method...