json2typescript icon indicating copy to clipboard operation
json2typescript copied to clipboard

Serialize JSON to enum.

Open sagarnayak opened this issue 6 years ago • 7 comments

I would like to convert a string to an enum type. lets say i have a enum.

enum Test{ YES="1", NO="0" }

and when i get {"value":"1"} from server i want to have YES in my typescript class not 1. is it possible?

sagarnayak avatar May 23 '18 08:05 sagarnayak

Yes, of course.

You need to check out the example of „custom converters“ in the ReadMe. If you follow this example, you should have no problems implementing your request.

andreas-aeschlimann avatar May 23 '18 12:05 andreas-aeschlimann

I was also thinking of that approach. but if you have worked with java you might know that we can just add the @SerializedName attribute to the enum constants. and it will auto parse from json according to its type and value. I was expecting something like that. anyways thanks for the help.

sagarnayak avatar May 24 '18 09:05 sagarnayak

json2typescript is as small as it can be. Therefore, no "magic" is happening under the hood. It could be possible that we support such a deserialization by default at some point, but for now you may easily implement it for yourself.

andreas-aeschlimann avatar May 24 '18 21:05 andreas-aeschlimann

Hi all, I wrote the following enum converter base class to help me out.

  export class EnumConverter<T> implements JsonCustomConvert<T> {
    validValues: string[];

    constructor(private enumType: unknown, private enumName: string) {
      this.validValues = Object.values(Object.getOwnPropertyDescriptors(enumType)).map(
        (value) => value.value
      );
    }

    deserialize(value: string): T {
      if (!this.validValues.includes(value)) {
        throw new Error(
          `JsonConvert error; invalid value for enum ${this.enumName}, expected one of '${this.validValues}', found '${value}'`
        );
      }
      return (value as unknown) as T;
    }

    serialize(data: T): any {
      return data;
    }
  }

Usage:

enum MyEnum {
  RED = "red",
  WHITE = "white",
  BLUE = "blue",
}

@JsonConverter
class MyEnumConverter extends EnumConverter<MyEnum> {
  constructor() {
    super(MyEnum, "MyEnum");
  }
}

Almar avatar Apr 23 '21 17:04 Almar

Thank you @Almar, very cool. Do you like to make a PR or shall I implement it occasionally?

andreas-aeschlimann avatar Apr 27 '21 23:04 andreas-aeschlimann

Hey @andreas-aeschlimann, It would be cool if I can contribute via a PR. I'll give it a try ;-)

Almar avatar May 05 '21 16:05 Almar

Nice! Please try to add some tests as well for enums.

andreas-aeschlimann avatar May 05 '21 20:05 andreas-aeschlimann