'creating an empty json object from dart object in flutter
I have a class
class User{
String name;
Address address;
}
and
class Address{
String houseId;
String location;
}
how can I make an empty address json object
"user":{"name":"jack","address":{}}
not
"user":{"name":"jack","address":{"houseId":null,"location",null}}
I am using json_annotation: ^3.0.1 -- build_runner: ^1.8.0 -- json_serializable: ^3.2.5
in flutter
Solution 1:[1]
You can add a checker on your json encoder to check if address contains values.
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
'name': instance.name,
'address': instance.address != null ? instance.address : {},
};
This should encode an empty map on the json if Address inside User is null.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Omatt |