Delphi Xe DataSetToObject by SuperObject

由于服务器使用的是php,经常需要使用json和对象间的互相转换,网上找了蛮久也没有找到需要的

自己草写了一个,Mark一下

function TMyDataTable.DatSetTojson: ISuperObject;
var
  itema: ISuperObject;
  i,j:Integer;
  f:TField;
begin
  result:=nil;
  if FQry.Active = false then exit;
  if FQry.RecordCount <>1 then exit;
  with fqry do
  begin
     First;
     itema:=SO();
     for i := 0 to Fields.Count-1 do
     begin
       f:= Fields[i];
       case f.DataType of
         ftString,ftMemo,ftFixedChar,ftWideString,ftFixedWideChar,ftWideMemo:
           begin
              if VarIsNull(FieldByName(f.FieldName).Value) then
              itema.S[Fields[i].FieldName]:=''
              else
              itema.S[Fields[i].FieldName]:=FieldByName(f.FieldName).AsString;
           end
       else
           begin
             if VarIsNull(FieldByName(f.FieldName).Value) then
              itema.S[Fields[i].FieldName]:='0'
             else
              itema.S[Fields[i].FieldName]:=FieldByName(f.FieldName).AsString;
           end;
       end

     end;
  end;
  result:=itema;
end; 

使用此函数实现Dataset到json的转换

function TMyDataTable.JsonToObj<T>(json: ISuperObject): T;
begin
  if mctx = nil then
  mctx:=TSuperRttiContext.Create;
  result:=mctx.AsType<T>(json);
end; 

使用此函数实现JsonToObj的转换

function TMyDataTable.objToJson<T>(obj:T):Isuperobject;
begin
  if mctx = nil then
  mctx:=TSuperRttiContext.Create;
  mctx:=TSuperRttiContext.Create;
  result:=mctx.AsJson<T>(obj);
end;

使用此函数实现ObjectToJson的转换

function TMyDataTable.JsonToObj<T>(json: ISuperObject): T;
begin
  if mctx = nil then
  mctx:=TSuperRttiContext.Create;
  result:=mctx.AsType<T>(json);
end;

使用此函数实现JsonToObject的转换

至此本地客户端与服务器和数据库之间的数据交换就全部实现了,不过这些函数只做一条record的处理

暂时先够自己用了,如果您发现网上有更好的库麻烦转告一下谢谢



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值