Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
lukehutch opened this issue Dec 30, 2023 · 2 comments
Closed

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

lukehutch opened this issue Dec 30, 2023 · 2 comments

Comments

@lukehutch
Copy link

lukehutch commented Dec 30, 2023

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
Copy link

Can't you just set includeIfNull to false?

@lukehutch
Copy link
Author

I didn't know about that. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants