上代码。
unit uPerson; interface uses Data.DBXJSONReflect, Data.DBXJSON, System.SysUtils; type TPerson = class FirstName: string; LastName: string; Age: Integer; end; TPersonArray = array of TPerson; function JSONMarshal(persons: TPersonArray): TJSONArray; function JSONUnMarshal(persons: TJSONArray): TPersonArray; implementation function JSONMarshal(persons: TPersonArray): TJSONArray; var i: Integer; mar: TJSONMarshal; jsonPerson: TJSONObject; begin Result := TJSONArray.Create; mar := TJSONMarshal.Create(TJSONConverter.Create); for i := Low(persons) to High(persons) do begin jsonPerson := mar.Marshal(persons[i]) as TJSONObject; Result.AddElement(jsonPerson); end; FreeAndNil(mar); end; function JSONUnMarshal(persons: TJSONArray): TPersonArray; var i: Integer; unmar: TJSONUnMarshal; person: TPerson; begin SetLength(Result, persons.Size); unmar := TJSONUnMarshal.Create; for i := 0 to persons.Size - 1 do begin person := unmar.Unmarshal(persons.Get(i)) as TPerson; Result[i] := person; end; FreeAndNil(unmar); end; end.服务器端代码
function TServerMethods1.GetPersons: TJSONArray; var i: Integer; persons: TPersonArray; begin SetLength(persons, 3); for i := Low(persons) to High(persons) do begin persons[i] := TPerson.Create; with persons[i] do begin FirstName := 'zzz' + Chr(Ord('A') + Random(20)); LastName := 'yyy' + Chr(Ord('a') + Random(20)); Age := Random(80); end; end; Result := JSONMarshal(persons); for i := Low(persons) to High(persons) do persons[i].Free; end;客户端代码
procedure TForm1.btn1Click(Sender: TObject); var persons: TPersonArray; i: Integer; begin persons := JSONUnMarshal(FServerMethod.GetPersons); mmo1.Clear; for i := Low(persons) to High(persons) do with persons[i] do begin mmo1.Lines.Add(Format('FirstName=%s, LastName=%s, Age=%d', [FirstName, LastName, Age])); Free; end; end;
没有评论:
发表评论