google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.55k stars 396 forks source link

Why it's impossible to get the JsonValue of the enum? #1283

Closed c0dezli closed 1 year ago

c0dezli commented 1 year ago

Let's say we have a enum defined as following:

import 'package:json_annotation/json_annotation.dart';

enum SurveyQuestionEnum {
  @JsonValue(r'Company Admin NPS Rating')
  companyAdminNPSRating,
}

How can I get 'Company Admin NPS Rating' in code?? It seems like it's impossible

SurveyQuestionEnum.companyAdminNPSRating.toString()
// prints SurveyQuestionEnum.companyAdminNPSRating

SurveyQuestionEnum.companyAdminNPSRating.name
// prints companyAdminNPSRating

Why can't extend the enum to have a getter like jsonValue so the following is possible?

SurveyQuestionEnum.companyAdminNPSRating.jsonValue
// prints  'Company Admin NPS Rating' 
c0dezli commented 1 year ago

I'm either not looking at the right place or the documentation of this package is very bad. I even looked through the source code but I still have no clue why this is not possible

kevmoo commented 1 year ago

I think you need to use the "enhanced enum" features.

See https://github.com/google/json_serializable.dart/blob/master/json_serializable/test/integration/json_enum_example.dart#L29

c0dezli commented 1 year ago

But it still can't convert enum value to string. Where is a code snippet I can follow? I have read the source code it didn't help

kevmoo commented 1 year ago

But it still can't convert enum value to string. Where is a code snippet I can follow? I have read the source code it didn't help

Add a custom toString() to your enum - see https://codewithandrea.com/tips/dart-2.17-enums-with-members/