Recent

Author Topic: Serialize/DeSerialize generic.collection type to from JSON  (Read 261 times)

franko_nd

  • Newbie
  • Posts: 1
Serialize/DeSerialize generic.collection type to from JSON
« on: February 03, 2023, 12:31:29 pm »
Hello!

Help, please.

System OS Windows 7 x64.
FPC 3.3.1 in CodeTyphon 8.0.

I have JSON (TJSOnData) :
[{ "id" : "87DC528AF55142CFBB019D98F5ABD0D8", "value" : 178 }, { "id" : "37A2B479C1BE46E8BBC11E05C5BAB75C", "value" : 89 }, { "id" : "7BBA5B77595A4141B7E994473CDAFE39", "value" : 16 }, { "id" : "9A946B8A373344ADBD789D75E7572A03", "value" : 80 }, { "id" : "665D45735D354DBF9A0C665E07BBEA7E", "value" : 90 }]

Need deserialize this JSON to TListValueBaseParam = class(TList<TValueBaseParam>).
And need serialize TListValueBaseParam to JSON.

Description class :

  TValueBaseParam = record
   ID                 : String;
   Value              : Double;
   procedure Clear();
  end;

  TListValueBaseParam = class(TList<TValueBaseParam>)
   function IndexOfID(ID: String): Integer;overload;
   procedure ToMemory(MemData: TMemoryStream);
   procedure FromMemory(MemData: TMemoryStream);
   ...
  end;

Zvoni

  • Hero Member
  • *****
  • Posts: 1685
Re: Serialize/DeSerialize generic.collection type to from JSON
« Reply #1 on: February 03, 2023, 01:12:06 pm »
FPC 3.3.1 in CodeTyphon 8.0.
Ask in CodeTyphoon-Forum....
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad

paweld

  • Hero Member
  • *****
  • Posts: 635
Re: Serialize/DeSerialize generic.collection type to from JSON
« Reply #2 on: February 03, 2023, 01:25:00 pm »
I don't know how to deserialize to generics.collection, but an example of deserialization to TCollection is in the appendix. 

Edit: if you don't want to save the TCollection to an object, but directly as an array then modify the procedure that saves to JSON to:
Code: Pascal  [Select][+][-]
  1. function TListValueBaseParam.SaveToJSON: String;var
  2.   js: TJSONStreamer;
  3. begin
  4.   Result := '';
  5.   js := TJSONStreamer.Create(nil);
  6.   try
  7.     Result := js.CollectionToJSON(Self); //instead of: js.ObjectToJSONString(Self);
  8.   except
  9.     js.Free;
  10.   end;
  11. end;
  12.  
« Last Edit: February 03, 2023, 01:47:34 pm by paweld »
Best regards / Pozdrawiam
paweld

 

TinyPortal © 2005-2018