Junior — Middle
How is data conversion to JSON format carried out in your application?
sobes.tech AI
Answer from AI
In Flutter, the dart:convert library is commonly used to convert data to JSON format. The model object is first converted into a Map using the toJson() method, and then serialized into a JSON string using the jsonEncode() function.
Example:
import 'dart:convert';
class User {
String name;
int age;
User(this.name, this.age);
Map<String, dynamic> toJson() => {
'name': name,
'age': age,
};
}
void main() {
User user = User('Alice', 30);
String jsonString = jsonEncode(user.toJson());
print(jsonString); // {"name":"Alice","age":30}
}