google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.55k stars 397 forks source link

Omit properties from `toJson()` when value is null #1385

Closed lukehutch closed 9 months ago

lukehutch commented 9 months ago

Given a serializable class with nullable fields firstName and lastName:

@JsonSerializable()
class Person {
  final String? firstName, lastName;

  Person({required this.firstName, required this.lastName});

  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

currently the code generator generates the following toJson method given a nullable field someNullableField:

Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
      'firstName': instance.firstName,
      'lastName': instance.lastName,
    };

I don't know if null values are serialized into a JSON string as

{ "someNullableField": null }

of if the map entry is simply omitted by the JSON string serializer when the value is null, but either way, it would be more optimal in terms of time and space to only add non-null fields to the map:

Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
      if (instance.firstName != null) 'firstName': instance.firstName,
      if (instance.lastName != null) 'lastName': instance.lastName,
    };

Related:

jtmuller5 commented 9 months ago

Can't you just set includeIfNull to false?

lukehutch commented 9 months ago

I didn't know about that. Thank you!