-
Notifications
You must be signed in to change notification settings - Fork 54
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Serialize JSON to enum. #67
Comments
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. |
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, 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, |
Nice! Please try to add some tests as well for enums. |
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?
The text was updated successfully, but these errors were encountered: