To generate a JSON parent in an API in Dart, you can define a class with the properties you want to include in the JSON object. You can then use the jsonEncode
function from the dart:convert
library to convert the class instance to JSON format.
Here's an example:
import 'dart:convert';
class Person {
String name;
int age;
Person({required this.name, required this.age});
Map<String, dynamic> toJson() {
return {
'name': name,
'age': age,
};
}
}
void main() {
Person person = Person(name: 'John', age: 30);
String jsonStr = jsonEncode(person.toJson());
print(jsonStr); // {"name":"John","age":30}
}
In this example, Person
is defined as a class with two properties: name
and age
. The toJson
method returns a Map<String, dynamic>
object with the same properties as keys and their values.
When an instance of Person
is created, it can be converted to a JSON string by calling jsonEncode
with the result of toJson
. The resulting string will have the same structure as the Map
returned by toJson
, with property names as keys and their values.
Asked: 2023-01-06 11:00:00 +0000
Seen: 11 times
Last updated: Aug 31 '22