How to serialize an TList to Json without “garb

2019-07-18 07:00发布

问题:

I need to serialize this json sting to an Delphi class.

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

Here is my class:

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.

I'm using TJson.ObjectToJsonString(TMyClass) and TJson.JsonToObject<TMyClass>(AJsonString).

My problem is that a lot of garbage is generated when serializing an TList<TDetails> type. For example

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

It's fine when using an TArray<TDetails> type instead but I'll loose all TList feature.

How can I still use TList type and get a correct Json output ?