DataSetToJson JsonToDataSet

原创
2019/06/12 08:46
阅读数 465
function _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;

procedure _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.Count - 1 do
  begin
    ADataset.Append;
    jRecord := jDataSet.Items[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;

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部