Json_serializable.dart: `unknownEnumValue` does not support enum collections

Created on 3 Jan 2020  Â·  8Comments  Â·  Source: google/json_serializable.dart

enum TestEnum {
  cat,
  unknown,
}

@JsonSerializable()
class TestEntity {
  @JsonKey(unknownEnumValue: TestEnum.unknown)
  final List<TestEnum> list;

  factory TestEntity.fromJson(Map<String, dynamic> json) =>
      _$TestEntityFromJson(json);

  Map<String, dynamic> toJson() => _$TestEntityToJson(this);
}
[INFO] Running build...
[SEVERE] json_serializable:json_serializable on lib/test.dart:
Error running JsonSerializableGenerator
Error with `@JsonKey` on `list`. `unknownEnumValue` can only be set on fields of type enum.
test.dart:9:24
   â•·
 9 │   final List<TestEnum> list;
   │                        ^^^^
   ╵
[INFO] Running build completed, took 43ms

I think the solution mentioned in this comment is better: https://github.com/dart-lang/json_serializable/issues/504#issuecomment-509530737

P3 low help wanted enhancement

All 8 comments

This feature was not designed to handle collections of enums. I consider this a feature request.

@JsonKey(unknownEnumValue: TestEnum.unknown)
TestEnum list;

The same issue, is it deliverable in the near future?

The same issue, is it deliverable in the near future?

This is not a high priority for me. I may consider a pull request if it's clean and introduces minimal churn.

Is it possible to support this too? Map ratings;

Any news on this @kevmoo ?
I really enjoy this library and the unknownEnumValue is very handy to protect my app. However, I have no work around to protect the app from API changes when I receive a list of enums.

I had a look in the source code and I would say that the code already supports this functionality. I say this because the LambdaResult.process(...) method inside the iterable helper deals with enums just like the "normal" enum fields.

However, there is a check that the unknownEnumValue JsonKey annotation can only be used for fields of type Enum.

This is in the json_key_utils.dart:

      if (mustBeEnum && !isEnum(element.type)) {
        throwUnsupported(
          element,
          '`$fieldName` can only be set on fields of type enum.',
        );
      }

If the condition would be adjusted to check if isEnumOrEnumIterable instead of just isEnum this error would not be thrown and the key would pass.

I am not familirialized with static code analyzis and this library to submit a PR while working on my other projects.

Hopefully somebody with more expertize can have a quick look and solve this in the future.

Was this page helpful?
0 / 5 - 0 ratings