Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TJsonObjectHelper
program JsonToEnumProject;
uses
System.SysUtils,
System.Json,
System.JSONConsts,
System.Rtti,
System.TypInfo;
type
TEnum = (one, two, three);
{$REGION 'TJsonObjectHelper'}
TJsonObjectHelper = class helper for System.Json.TJSONObject
function GetValue<T>(const APath: string): T;
end;
function TJsonObjectHelper.GetValue<T>(const APath: string): T;
var
enumInfo: PTypeInfo;
enumAsString: String;
enumAsInteger: Integer;
begin
enumInfo := TypeInfo(T);
if(enumInfo.Kind = TTypeKind.tkEnumeration) then
begin
enumAsString := GetValue<String>(APath);
enumAsInteger := GetEnumValue(enumInfo, enumAsString);
if(enumAsInteger <> -1) then
Result := TValue.FromOrdinal(enumInfo, enumAsInteger).AsType<T>()
else
raise EJSONException.CreateFmt(SNoConversionAvailableForValue, [enumAsString, enumInfo.Name]);
end
else
Result := inherited GetValue<T>(APath);
end;
{$ENDREGION}
const
input = '{"enum": "two"}';
var
jsonObject: TJSONObject;
enum: TEnum;
begin
jsonObject := (TJSONObject.ParseJSONValue(input) as TJSONObject);
try
enum := jsonObject.GetValue<TEnum>('enum');
Assert( enum = TEnum.two);
finally
jsonObject.Destroy();
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.