Is there a way to get the JSON enum value when using @JsonEnum(fieldRename)

797 Views Asked by At

I was searching a way to serialize & deserialize my enum with different cases (camelCase to snake_case) and I discovered the @JsonEnum parameter offered by the Json_serializable package.

That's exactly what I needed! It works perfectly for de-serialization (String to JSON) and should (not tested) for serialization too.

However I would like to know if there is a getter or function that allows to get the "string" representation of an enum value that takes in account the fieldRename parameter.

My use case concern a GET request where I will not convert my enum to JSON but only use its string value to pass it as ?param=<enum_value_str>

Example of what I am looking for

@JsonEnum(fieldRename: FieldRename.snake)
enum A {
   firstValue,
   secondValue,
   thirdValue,
}



print(A.name) // -> firstValue
print(A.toJson()) // This does not exist, the expected output -> first_value

If anybody has any idea on how to solve this it wuold be great!


As a workaround, I defined an extension that contains a method called str

extension AExtension on A {
     String get str {
        switch (this) {
          case A.firstValue:
             return 'first_value';
          case A.secondValue:
             return 'second_value';
          case A.thirdValue:
             return 'third_value';
        }
     }
}

That works but I think the fieldRename parameter would work way better if I can find a function to retrieve the "JSON string representation" of the enum value.

2

There are 2 best solutions below

1
On

you can use recase package so the code will look like this:

import 'package:recase/recase.dart';

enum A {
   firstValue,
   secondValue,
   thirdValue,
}
print(a.secondValue.name.snakeCase); // 'second_value'

P.S. that package have a lot handy cases

0
On

a.dart file

import 'package:json_annotation/json_annotation.dart';

part 'a.g.dart';

@JsonEnum(
  fieldRename: FieldRename.snake,
  alwaysCreate: true,
)
enum A {
  firstValue,
  secondValue,
  thirdValue;

  String toJson() => _$AEnumMap[this]!;
  factory A.fromJson(String json) =>
      _$AEnumMap.map((key, value) => MapEntry(value, key))[json]!;
}

a.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'a.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

const _$AEnumMap = {
  A.firstValue: 'first_value',
  A.secondValue: 'second_value',
  A.thirdValue: 'third_value',
};

Add alwaysCreate: true to JsonEnum annotation will create a toJson map for the enum even if it's not used in another place