procedure TForm1.btn4Click(Sender: TObject);const FieldName: array[1..3] of string = ('姓名','单位','地址'); FielValue: array[1..3] of string = ('张三','华为','广州');var blockCount, FieldCount, i, j: Integer; Doc, DocBlock, DocField: TDocVariantData; v1, Data: variant;begin Doc.Init; Doc.I['blockCount'] := 3; for i := 1 to 3 do begin DocBlock.Init; DocBlock.I['FieldCount'] := i; for j := 1 to i do begin DocField.Init; V1 := _Json(WideStringToUTF8(Format('{"Name":"%s","Value":["%s","%s","%s"]}', [ FieldName[j], FielValue[j] + '_1', FielValue[j] + '_2', FielValue[j] + '_3' ] ))); DocBlock.A_['fields']^.AddItem(v1); TDocVariantData(Data).InitJSON(DocBlock.ToJSON()); end; doc.A_['blocks']^.AddItem(Data); end; mmo1.Lines.Text := UTF8ToWideString(doc.ToJSON);end;{"blockCount":3,"blocks":[ {"FieldCount":1,"fields":[{"Name":"姓名","Value":["张三_1","张三_2","张三_3"]}]}, {"FieldCount":2,"fields":[{"Name":"姓名","Value":["张三_1","张三_2","张三_3"]},{"Name":"单位","Value":["华为_1","华为_2","华为_3"]}]}, {"FieldCount":3,"fields":[{"Name":"姓名","Value":["张三_1","张三_2","张三_3"]},{"Name":"单位","Value":["华为_1","华为_2","华为_3"]},{"Name":"地址","Value":["广州_1","广州_2","广州_3"]}]}]}
uses SynCommons;
前面的写法有内存泄漏,下面是修改好的代码:
procedure TForm1.btn4Click(Sender: TObject);const FieldName: array[1..3] of string = ('UserName','Department','Address'); FielValue: array[1..3] of string = ('Gets','Google','American');var i, j: Integer; Doc, DocBlock: TDocVariantData; v1, Data: variant;begin Doc.Init; Doc.I['blockCount'] := 3; for i := 1 to 3 do begin DocBlock.Init; DocBlock.I['FieldCount'] := i; for j := 1 to i do begin V1 := _Json(WideStringToUTF8(Format('{"Name":"%s","Value":["%s","%s","%s"]}', [ FieldName[j], FielValue[j] + '_1', FielValue[j] + '_2', FielValue[j] + '_3' ] ))); DocBlock.A_['fields']^.AddItem(v1); VarClear(v1); end; TDocVariantData(Data).InitJSON(DocBlock.ToJSON()); doc.A_['blocks']^.AddItem(Data); DocBlock.Clear; FreeAndNil(DocBlock); VarClear(Data); end; mmo1.Lines.Text := UTF8ToWideString(doc.ToJSON); doc.Clear; FreeAndNil(doc);end;