如何在没有“垃圾”的情况下将TList <t>序列化为Json </t>

时间:2015-03-26 10:35:51

标签: json delphi generics delphi-xe7 tlist

我需要将这个json sting序列化为Delphi类。

  {
    "Master":{
      "version":"1.0"
    },
    "Details":[
      {
        "idColisEntreeDetail":0,
        "codeBarre":"123456789"
      },
      {
        "idColisEntreeDetail":0,
        "codeBarre":"234567890"
      }
    ]
  }

这是我的班级:

unit unit2;

interface

uses Generics.Collections, Rest.Json;

type

  TDetails = class
  private
    FCodeBarre: String;
    FIdColisEntreeDetail: Extended;
  public
    property codeBarre: String read FCodeBarre write FCodeBarre;
    property idColisEntreeDetail: Extended read FIdColisEntreeDetail
      write FIdColisEntreeDetail;
  end;

  TMaster = class
  private
    FVersion: String;
  public
    property version: String read FVersion write FVersion;
  end;

  TMyClass = class
  private
    FDetails: TList<TDetails>;
    FMaster: TMaster;
  public
    property Details: TList<TDetails> read FDetails write FDetails;
    property Master: TMaster read FMaster write FMaster;
    constructor Create;
    destructor Destroy; override;
  end;

implementation

{ TDetails }


{ TMyClass }

constructor TMyClass.Create;
begin
  inherited;
  FMaster := TMaster.Create();
end;

destructor TMyClass.Destroy;
var
  LDetailsItem: TDetails;
begin

  for LDetailsItem in FDetails do
    LDetailsItem.free;

  FMaster.free;
  inherited;
end;

end.

我正在使用TJson.ObjectToJsonString(TMyClass)TJson.JsonToObject<TMyClass>(AJsonString)

我的问题是序列化TList<TDetails>类型时会产生大量垃圾。例如

  {
    "details":{
      "items":[
      {
        "idColisEntreeDetail":0,
        "codeBarre":"123456789"
      },
      {
        "idColisEntreeDetail":0,
        "codeBarre":"234567890"
      }
      ],
      "count":2,
      "arrayManager":{
      }
    },
    "master":{
      "version":""
    }
  }

使用TArray<TDetails>类型时很好,但我会松开所有TList功能。

我如何仍然使用TList类型并获得正确的Json输出?

0 个答案:

没有答案