#1 2022-07-21 11:13:47

Charly52
Member
From: Germany
Registered: 2022-07-20
Posts: 12

How can I serialize a nested record

I have the following structur:

type

   TIntArray = Array[1..5] of Integer;
   Ttestrec1 = record
      Int1      : Integer;
      String2 : String;
      feld1    : TIntArray
   end;

   TStrArray = Array[1..3] of String;
   Ttestrec2 = record
      Int2 : Integer;
      Int3 : Integer;
      feld2: TStrArray;
   end;

   Ttestrec3 = record
     rec1 : Ttestrec1;
     rec2 : TtestRec2;
   end;

var
  rec1 : Ttestrec1;
  rec2 : Ttestrec2;
  rec3 : TtestRec3;

How can I do an  "Automatic JSON serialization" of this structure of rec3?
And what must be used in the new  version2 Framework?
SynCommons.pas seems to be splitted

Regards Charly

Offline

#2 2022-07-21 11:45:27

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,272
Website

Re: How can I serialize a nested record

1) Ensure you use "packed record"
2) Prefer dynamic arrays instead of static arrays.
3) Nested records work with no problem.

On FPC and before 2010, you need to set the text definition for each type, because otherwise there is not enough RTTI.

Offline

#3 2022-07-22 08:35:16

Charly52
Member
From: Germany
Registered: 2022-07-20
Posts: 12

Re: How can I serialize a nested record

Thank you for this answer, but

1) Is the "packet record"  essential  or a recommendation?  I have to serialize an old SW with existing Types.
2) The same and in the moment no time to change the code.   :-(

Can you give me a little example on base of the  code in my question above (rec3 : TtestRec3;)

Danke Charly

Offline

#4 2022-07-22 13:21:43

igors233
Member
Registered: 2012-09-10
Posts: 234

Re: How can I serialize a nested record

> 1) Is the "packet record"  essential  or a recommendation?  I have to serialize an old SW with existing Types.

Essential.

If you're using Delphi try to see does it works with RecordSaveJSON and REcordLoadJSON.

> Can you give me a little example on base of the  code in my question above (rec3 : TtestRec3;)

Take a look at RegisterCustomJSONSerializerFromText procedure in code (some examples) and code examples from mORMot1 where RegisterCustomJSONSerializerFromText is used.

BTW if you have complex record structures I would suggest that you do not try to serialize/deserialize raw records/array at all.
Rather write a custom load/save method that converts your internal format to TDocVariantData (json format).

Offline

Board footer

Powered by FluxBB