google / google/json_serializable.dart

Handle the case where the setter is nullable by the getter is not

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

Description

Hi,
This is the first time I fill an issue what so ever.
Here is the situation:
I just migrated to null-safety and I decided that my model should return non null value even if they come from the server as null.
for instance: the IDs of entities are never null. so let's take that as an example here.
I put the id of my class as a private member and exposed it throw a getter and a setter.
The getter returns a non-null value (if the private _id is null, it fills that with an empty string)
the setter expects a nullable value (if the setter argument is null, a default empty string is set)
The issue is when json_serializable generates the code, it does not consider the setter parameter.
here is the code:

```dart
@JsonSerializable()
class BasicEntity {
BasicEntity();

String? _id;

@JsonKey(name: "_id")
String get id {
// <--- returns a non null value
return _id ?? "";
}

void set id(String? /*expects a nullable value that my come like that from the server*/ id) {
_id = (id ?? "");
}

factory BasicEntity.fromJson(Map json) => _$BasicEntityFromJson(json);
Map toJson() => _$BasicEntityToJson(this);
}
`

And here is the generated code
`BasicEntity _$BasicEntityFromJson(Map json) {
return BasicEntity()..id = json['_id'] as String; // <--- SHOULD BE String? (a nullable string because that is what the setter expects)
}

Map _$BasicEntityToJson(BasicEntity instance) =>
{
'_id': instance.id,
};
```

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.