google / google/json_serializable.dart

omit properties from toJson() when their value is an empty list

Open
#1,369 1 comment 4 reactions 0 assignees View on GitHub
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

I have a class like so (simplified/redacted):
```
class Source {
final String? url;
final List works;

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

Map 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?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.