Estos rutinas le darán una idea de como transformar un registro a JSON y de como llenar los datos de un registro de una tabla desde un objeto JSON.
function DataRowToJSONObject(const AValue : TDataSet): TJSONObject; var I: Integer; AString : String; begin Result := TJSONObject.Create(); for I := 0 to AValue.FieldDefs.Count-1 do begin case AValue.FieldDefs[I].DataType of ftString, ftWideString, ftMemo : begin if AValue.FieldByName(AValue.FieldDefs[I].Name).AsString <> '' then Result.AddPair(AValue.FieldDefs[I].Name, AValue.FieldByName(AValue.FieldDefs[I].Name).AsString) else Result.AddPair(AValue.FieldDefs[I].Name, ' '); end; ftSmallint, ftInteger, ftWord, ftLongWord, ftShortint : begin Result.AddPair(AValue.FieldDefs[I].Name, TJSONNumber.Create(AValue.FieldByName(AValue.FieldDefs[I].Name).AsInteger)); end; ftFloat, ftCurrency : begin Result.AddPair(AValue.FieldDefs[I].Name, TJSONNumber.Create(AValue.FieldByName(AValue.FieldDefs[I].Name).AsFloat)); end; ftBoolean : begin Result.AddPair(AValue.FieldDefs[I].Name, AValue.FieldByName(AValue.FieldDefs[I].Name).AsString) end; end; end; end; function JSONObjectToDataRow(const AJson : TJSONObject; const AValue : TDataSet): Boolean; var I: Integer; begin Result := False; for I := 0 to AValue.FieldDefs.Count - 1 do begin case AValue.FieldDefs[I].DataType of ftString, ftWideString, ftMemo : begin AValue.FieldByName(AValue.FieldDefs[I].Name).AsString := AJson.Get(AValue.FieldDefs[I].Name).JsonValue.Value; end; ftSmallint, ftInteger, ftWord, ftLongWord, ftShortint : begin AValue.FieldByName(AValue.FieldDefs[I].Name).AsInteger := (AJson.Get(AValue.FieldDefs[I].Name).JsonValue as TJsonNumber).AsInt; end; ftFloat, ftCurrency : begin AValue.FieldByName(AValue.FieldDefs[I].Name).AsFloat := (AJson.Get(AValue.FieldDefs[I].Name).JsonValue as TJsonNumber).AsDouble; end; ftBoolean : begin AValue.FieldByName(AValue.FieldDefs[I].Name).AsBoolean := StrToBool(AJson.Get(AValue.FieldDefs[I].Name).JsonValue.Value); end; end; end; end; |