Recent

Author Topic: TJSONDestreamer work with array  (Read 1059 times)

yus

  • New Member
  • *
  • Posts: 47
TJSONDestreamer work with array
« on: July 20, 2021, 10:23:40 pm »
It try deserialize JSON string.
Code: Pascal  [Select][+][-]
  1. JSON = '{"myarray": [100, 200, 300]}';

Documentation https://wiki.freepascal.org/Streaming_JSON

How correct write TCollectionItem class?

Now i have this code
Code: Pascal  [Select][+][-]
  1. unit Unit1;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. interface
  6.  
  7. uses
  8.   Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, fpjsonrtti, TypInfo, fpjson, Generics.Collections;
  9.  
  10. const
  11.   JSON = '{"myarray": [100, 200, 300]}';
  12.  
  13. type
  14.   TmyList = specialize TList<integer>;
  15.  
  16.   { TForm1 }
  17.  
  18.   TForm1 = class(TForm)
  19.     Button1: TButton;
  20.     procedure Button1Click(Sender: TObject);
  21.   private
  22.     procedure restoreNotify(Sender: TObject; AObject: TObject; Info: PPropInfo; AValue: TJSONData; var Handled: boolean);
  23.  
  24.   public
  25.  
  26.   end;
  27.  
  28.   { TmyObject }
  29.  
  30.   TmyObject = class(TCollectionItem)
  31.   private
  32.     Fmyarray: TmyList;
  33.   public
  34.     constructor Create(ACollection: TCollection); override;
  35.     destructor Destroy; override;
  36.   published
  37.     property myarray: TmyList read Fmyarray write Fmyarray;
  38.   end;
  39.  
  40.  
  41. var
  42.   Form1: TForm1;
  43.  
  44. implementation
  45.  
  46. {$R *.lfm}
  47.  
  48. { TmyObject }
  49.  
  50. constructor TmyObject.Create(ACollection: TCollection);
  51. begin
  52.   inherited Create(ACollection);
  53.   Fmyarray := TmyList.Create;
  54. end;
  55.  
  56. destructor TmyObject.Destroy;
  57. begin
  58.   FreeAndNil(Fmyarray);
  59.   inherited Destroy;
  60. end;
  61.  
  62. { TForm1 }
  63.  
  64. procedure TForm1.Button1Click(Sender: TObject);
  65. var
  66.   deser: TJSONDeStreamer;
  67.   myobject: TmyObject;
  68. begin
  69.   deser := TJSONDeStreamer.Create(nil);
  70.   myobject := TmyObject.Create(nil);
  71.   deser.OnRestoreProperty := @restoreNotify;
  72.   deser.JSONToObject(JSON, myobject);
  73.   ShowMessage(myobject.myarray.Count.ToString);
  74.   FreeAndNil(deser);
  75. end;
  76.  
  77. procedure TForm1.restoreNotify(Sender: TObject; AObject: TObject; Info: PPropInfo; AValue: TJSONData; var Handled: boolean);
  78. var
  79.   i: integer;
  80. begin
  81.   for i := 0 to TJSONArray(AValue).Count - 1 do
  82.     TmyObject(AObject).myarray.Add(TJSONArray(AValue).Items[i].AsInteger);
  83. end;
  84.  
  85. end.

But I don't like the handler OnRestoreProperty.
May be have another way?

Thank you.

 

TinyPortal © 2005-2018