google / google/json_serializable.dart

Incorrect nullable enum deserialization behavior

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

Description

Hello, recently we encountered incorrect behavior of parsing nullable enumeration by **json_annotation** generated code.

I guess you should return `null` in `$enumDecodeNullable` function in **enum_helper** instead of `ArgumentError()` when the `unknownValue` is null. Since this is a **nullable enum** case and **it should be null** as a fallback value.

```dart
if (unknownValue == null) {
throw ArgumentError( // here
'`$source` is not one of the supported values: '
'${enumValues.values.join(', ')}',
);
}
```

In our case we have different API versions and there are cases when API uses unsupported enum values, and this is expected from the mobile app perspective, so the value is defined as nullable enum in the model in our mobile app. But with your implementation the app crashes if the mapping fails.

Ex.:

```dart
@JsonSerializable()
class Dto {
@JsonKey(name: 'FeatureVersion')
final FeatureVersion? featureVersion;
}

enum FeatureVersion {
@JsonValue(1)
first,
@JsonValue(2)
second,
@JsonValue(3)
third,
}
```

There is a workaround to handle that case by setting `unknownEnumValue: JsonKey.nullForUndefinedEnumValue` in the `@JsonKey` annotation but I guess it is redundant for **nullable enums** any way.

> As a general concern I would suggest to introduce a special type exception for invalid enum mapping, for example for non nullable enums (function `$enumDecode`) and avoid using `ArgumentError`. Since it's not expected to catch errors in dart code, but the API contract mismatch is a common situation so it should be represented by exception to be able to be catched and handled.

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.