type
TGUIDConverter =
class(TJsonConverter)
public
function CanConvert(ATypeInfo: PTypeInfo): Boolean;
override;
function ReadJson(
const AReader: TJsonReader; ATypeInf: PTypeInfo;
const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue;
override;
procedure WriteJson(
const AWriter: TJsonWriter;
const AValue: TValue;
const ASerializer: TJsonSerializer);
override;
end;
function TGUIDConverter.CanConvert(ATypeInfo: PTypeInfo): Boolean;
begin
Result := ATypeInfo = System.TypeInfo(TGUID);
end;
function TGUIDConverter.ReadJson(
const AReader: TJsonReader;
ATypeInf: PTypeInfo;
const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue;
begin
Result := TValue.From(TGuid.Create(AReader.Value.AsString));
end;
procedure TGUIDConverter.WriteJson(
const AWriter: TJsonWriter;
const AValue: TValue;
const ASerializer: TJsonSerializer);
begin
AWriter.WriteValue(AValue.AsType<TGUID>);
end;
type
TFooBar =
class
GUID: TGUID;
end;
procedure Main;
begin
var foobar := TFooBar.Create;
foobar.GUID := TGUID.NewGuid;
Writeln(foobar.GUID.ToString);
var lSerializer := TJsonSerializer.Create;
lSerializer.Converters.Add(TGUIDConverter.Create);
var lJson := lSerializer.Serialize(foobar);
Writeln(lJson);
var newFooBar := lSerializer.Deserialize<TFooBar>(lJson);
Writeln(newFooBar.GUID.ToString);
end;