unit FMX.DataSetToJSON; interface uses FireDAC.Comp.Client,Data.DB; function DataSetToJSON(DataSet:TDataSet):String; function JSONToDataSet(JSONTEXT:String):TFDMemTable; implementation uses System.Rtti,System.JSON; function DataSetToJSON(DataSet:TDataSet):String; var I:integer; JSONObject,FieldJSONObject:TJSONObject; JSONArray:TJSONArray; begin Result:=''; JSONObject:=TJSONObject.ParseJSONValue('{}') as TJSONObject; try JSONObject.AddPair('Fields',TJSONArray.Create); JSONArray:=JSONObject.GetValue('Fields') as TJSONArray; for I := 0 to DataSet.FieldDefs.Count -1 do begin FieldJSONObject:=TJSONObject.Create ; FieldJSONObject.AddPair ('FieldName',DataSet.FieldDefs[i].Name ); FieldJSONObject.AddPair('DataType',TRttiEnumerationType.GetName<TFieldType>(DataSet.FieldDefs[i].DataType)); FieldJSONObject.AddPair('DataSize',TJSONNumber.Create(DataSet.FieldDefs[i].Size)); JSONArray.Add(FieldJSONObject) ; end; DataSet.First ; JSONObject.AddPair('DATAS',TJSONArray.Create); JSONArray:=JSONObject.GetValue('DATAS') as TJSONArray; while not DataSet.Eof do begin FieldJSONObject:=TJSONObject.Create ; for I := 0 to DataSet.FieldDefs.Count -1 do FieldJSONObject.AddPair(DataSet.FieldDefs[i].Name,DataSet.Fields[i].AsString); JSONArray.Add(FieldJSONObject) ; DataSet.Next ; end; Result := JSONObject.ToJSON ; finally JSONObject.Free ; end; end; function JSONToDataSet(JSONTEXT:String):TFDMemTable; var I,R:integer; JSONObject,FieldJSONObject:TJSONObject; JSONArray:TJSONArray; DataName,DataType:String; FieldType:TFieldType; FieldSize:integer; begin Result:=TFDMemTable.Create(nil); if JSONTEXT='' then Exit; JSONObject:=TJSONObject.ParseJSONValue(JSONTEXT) as TJSONObject; try JSONArray:=JSONObject.GetValue('Fields') as TJSONArray; for I := 0 to JSONArray.size -1 do begin Result.FieldDefs.Add(((JSONArray.Get(i) as TJSONObject).GetValue('FieldName') as TJSONString).Value, TRttiEnumerationType.GetValue<TFieldType>(((JSONArray.Get(i) as TJSONObject).GetValue('DataType') as TJSONString).Value), ((JSONArray.Get(i) as TJSONObject).GetValue('DataSize') as TJSONNumber).AsInt64); end; Result.CreateDataSet ; JSONArray:=JSONObject.GetValue('DATAS') as TJSONArray; for I := 0 to JSONArray.size -1 do begin Result.Append ; for R := 0 to Result.FieldDefs.Count -1 do begin FieldJSONObject:=(JSONArray.Get(i) as TJSONObject); if FieldJSONObject=nil then continue; try Result.FieldByName(Result.FieldDefs[R].Name).Value := (FieldJSONObject.GetValue(Result.FieldDefs[R].Name) as TJSONString).Value ; Except end; end; Result.Post ; end; finally JSONObject.Free ; end; end; end.