ADDED support for enumeration types in System.JSON based serializer

This commit is contained in:
Daniele Teti 2017-07-12 01:02:23 +02:00
parent e52aacc391
commit 8eb55556bc
3 changed files with 61 additions and 1 deletions

View File

@ -262,7 +262,9 @@ begin
AJSONObject.AddPair(AName, TJSONBool.Create(False));
end
else
AJSONObject.AddPair(AName, TJSONNumber.Create(AValue.AsOrdinal));
begin
AJSONObject.AddPair(AName, GetEnumName(AValue.TypeInfo, AValue.AsOrdinal));
end;
end;
tkClass:
@ -602,6 +604,9 @@ begin
else if (AValue.TypeInfo = System.TypeInfo(TTime)) then
AValue := TValue.From<TTime>(ISOTimeToTime(AJSONObject.Values[AName].Value))
else if (AValue.Kind = tkEnumeration) then
TValue.Make(GetEnumValue(AValue.TypeInfo, AJsonObject.Values[AName].Value), AValue.TypeInfo, AValue)
else
AValue := TValue.From<string>(AJSONObject.Values[AName].Value);
end;

View File

@ -188,6 +188,22 @@ type
property Name: string read FName write FName;
end;
TColorEnum = (RED, GREEN, BLUE);
TEntityWithEnums = class
private
FId: Int64;
FCode: Integer;
FName: string;
FColor: TColorEnum;
public
property Id: Int64 read FId write FId;
property Code: Integer read FCode write FCode;
property Name: string read FName write FName;
property Color: TColorEnum read FColor write FColor;
end;
[MVCSerialize(stFields)]
TEntitySerializeFields = class
private

View File

@ -70,6 +70,8 @@ type
procedure TestDeserializeEntitySerializationType;
procedure TestDeserializeCollection;
procedure TestDeserializeDataSet;
{ full cycle }
procedure TestSerializeDeSerializeEntityWithEnums;
end;
TMVCEntityCustomSerializerJSON = class(TInterfacedObject, IMVCTypeSerializer)
@ -1029,6 +1031,43 @@ begin
end;
end;
procedure TMVCTestSerializerJSON.TestSerializeDeSerializeEntityWithEnums;
const
JSON =
'{' +
'"Id":1,' +
'"Code":2,' +
'"Name":"Daniele Teti",' +
'"Color":"RED"' +
'}';
var
O: TEntityWithEnums;
S: string;
begin
O := TEntityWithEnums.Create;
try
O.Id := 1;
O.Code := 2;
O.Name := 'Daniele Teti';
O.Color := TColorEnum.RED;
S := FSerializer.SerializeObject(O);
CheckEqualsString(JSON, S);
finally
O.Free;
end;
O := TEntityWithEnums.Create;
try
FSerializer.DeserializeObject(S, O);
CheckEquals(1, O.Id);
CheckEquals(2, O.Code);
CheckEquals('Daniele Teti', O.Name);
CheckEquals(Ord(TColorEnum.RED), Ord(O.Color));
finally
O.Free;
end;
end;
procedure TMVCTestSerializerJSON.TestSerializeNill;
begin
CheckEquals('null', FSerializer.SerializeObject(nil));