{*******************************************************} { } { Tocsg.Json } { } { Copyright (C) 2020 kkuzil } { } {*******************************************************} unit Tocsg.Json; interface uses Tocsg.Obj, SysUtils, WinApi.Windows, Rtti, TypInfo, superobject; // http://www.progdigy.com/?page_id=6, http://superobject.googlecode.com/svn/trunk/ type TValueArray = array of TValue; TTgJson = class(TTgObject) public class function GetDataAsType(O: ISuperObject; const sPath: String = ''): T; class function ValueToJsonObject(aValue: T): ISuperObject; class function ValueToJsonAsString(aValue: T): String; {$IF CompilerVersion > 21} class function ArrayToJsonObject(aValues: TArray): ISuperObject; class function ArrayToJsonAsString(aValues: TArray): String; {$IFEND} end; implementation uses Tocsg.Safe; { TTgJson } class function TTgJson.GetDataAsType(O: ISuperObject; const sPath: String = ''): T; var ctx: TSuperRttiContext; begin Guard(ctx, TSuperRttiContext.Create); try if sPath = '' then Result := ctx.AsType(O) else Result := ctx.AsType(O[sPath]); except // end; end; class function TTgJson.ValueToJsonObject(aValue: T): ISuperObject; var v: TValue; ctx: TSuperRttiContext; begin v := TValue.From(aValue); ctx := TSuperRttiContext.Create; try Result := ctx.ToJson(v, SO); finally FreeAndNil(ctx); end; end; class function TTgJson.ValueToJsonAsString(aValue: T): String; var O: ISuperObject; begin O := ValueToJsonObject(aValue); // Result := O.AsString; Result := O.AsJson; end; {$IF CompilerVersion > 21} class function TTgJson.ArrayToJsonObject(aValues: TArray): ISuperObject; var v: TValue; i, nCnt: Integer; ValueArray: TValueArray; ctx: TSuperRttiContext; rctx: TRttiContext; rtype: TRttiType; begin nCnt := Length(aValues); SetLength(ValueArray, nCnt); rctx := TRttiContext.Create; try for i := 0 to nCnt - 1 do ValueArray[i] := TValue.From(aValues[i]); rtype := rctx.GetType(TypeInfo(TArray)); v := TValue.FromArray(rtype.Handle, ValueArray); Guard(ctx, TSuperRttiContext.Create); Result := ctx.ToJson(v, SO); finally rctx.Free; SetLength(ValueArray, 0); end; end; class function TTgJson.ArrayToJsonAsString(aValues: TArray): String; var O: ISuperObject; begin O := ArrayToJsonObject(aValues); Result := O.AsString; end; {$IFEND} end.