使用DELPHI原生类实现数据集和JSON相互转换
JSON二要素:数组和对象。对象可以包含数组,数组可以包含对象。无层数限制。OLEVARIANT也类似,OLEVARIANT的一个元素又可以是OLEVARIANT,且无层数限制。XML亦类似。这也是它们能序列一切对象的奥秒所在。 JSON就是字符串,定义好序列后的字符串格式,甚至都不需要啥JSON类库,就可以自行组装JSON字符串和解析JSON字串获取数据。
USES System.JSON
1)数据集转换为JSON字符串:
function TForm1.DataSetToJson(ADataset: TDataSet): string;
// [{"CityId":"18","CityName":"西安"},{"CityId":"53","CityName":"广州"}]var LRecord: string; LField: TField; i: integer;begin Result := ''; if (not ADataset.Active) or (ADataset.IsEmpty) then Exit; Result := '['; ADataset.DisableControls; ADataset.First; while not ADataset.Eof do begin for i := 0 to ADataset.FieldCount - 1 do begin LField := ADataset.Fields[i]; if LRecord = '' then LRecord := '{"' + LField.FieldName + '":"' + LField.Text + '"' else LRecord := LRecord + ',"' + LField.FieldName + '":"' + LField.Text + '"'; if i = ADataset.FieldCount - 1 then begin LRecord := LRecord + '}'; if Result = '[' then Result := Result + LRecord else Result := Result + ',' + LRecord; LRecord := ''; end; end; ADataset.Next; end; ADataset.EnableControls; Result := Result + ']';end;2)JSON字符串转换为数据集:
procedure TForm1.JsonToDataSet(AJson: string; ADataset: TDataSet);
var jDataSet: TJSONArray; jRecord: TJSONObject; i, j: Integer;begin if (AJson = '') or (ADataset = nil) or (not ADataset.Active) then Exit; jDataSet := TJSONObject.Create.ParseJSONValue(AJson, True) as TJSONArray; while not ADataset.Eof do ADataset.Delete; for i := 0 to jDataSet.Size - 1 do begin ADataset.Append; jRecord := jDataSet.Get(i) as TJSONObject; for j := 0 to ADataset.FieldCount - 1 do ADataset.Fields[j].Text := jRecord.GetValue(ADataset.Fields[j].FieldName).ToString; ADataset.Post; end;end;