由于服务器使用的是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的处理
暂时先够自己用了,如果您发现网上有更好的库麻烦转告一下谢谢