json2typescript
json2typescript copied to clipboard
Serialize JSON to enum.
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?
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.
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.
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.
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");
}
}
Thank you @Almar, very cool. Do you like to make a PR or shall I implement it occasionally?
Hey @andreas-aeschlimann, It would be cool if I can contribute via a PR. I'll give it a try ;-)
Nice! Please try to add some tests as well for enums.