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 their value is an empty list #1369

Open Dieterbe opened 10 months ago

Dieterbe commented 10 months ago

I have a class like so (simplified/redacted):

class Source {
  final String? url;
  final List<String> works;

  Source({
    required this.url,
    required this.works,
  });

  Map<String, dynamic> toJson() => {
        if (url != null) 'url': url,
        if (works.isNotEmpty) 'works': works,
      };

I want to transition from my own handwritten toJson(), to a generated one. for the url field i can use the includeIfNull: false option, but for the 2nd field, is there a similar option to omit lists if they are empty? i see no such option?

Likewise, is it possible to tolerate such a field not being set when decoding json, and setting it to [] on the object?

lukehutch commented 9 months ago

I added #1385 which is related to this.

What you propose would work for fields of type List<String>, but not List<String>? (although I think it's still a good idea for non-nullable lists, to save on serialization time and space).

This could be extended to other "empty types" such as the empty string (for String-typed fields that are not nullable), and even the integer value 0 (for numerical fields that are not nullable).

Also related: #1340