creating an empty json object from dart object in flutter

Viewed 1451

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

1 Answers

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.

Related