#1 2018-07-30 14:28:54

ComingNine
Member
Registered: 2010-07-29
Posts: 294

How to serialize record with enum property ?

As shown in the gist code , the call to TTextWriter.RegisterCustomJSONSerializerFromText fails if the record definition contains enum type: ESynException 'Unregistered ptCustom for TJSONRecordTextDefinition.AddItem(E: TMYENUM)'.

Could you help to comment the correct way to deal with record type with enum property in JSON serialization ?
Many thanks !

Last edited by ComingNine (2018-07-30 14:30:09)

Offline

#2 2018-07-30 14:54:04

ComingNine
Member
Registered: 2010-07-29
Posts: 294

Re: How to serialize record with enum property ?

From your documentation , it is suggested that "For other types (like enumerations or sets), you can simply use the unsigned integer types corresponding to the binary value, e.g. byte word cardinal Int64 (depending on the sizeof() of the initial value)." With such treatment, the updated gist code serializes the enum property within the record as unsigned integer.

Nevertheless, the enum property within the TObject can be serialized to human readable text, could you help to comment whether it is possible to serialize enum property within the record also as human readable text ?

{
        "E": 0,
        "K": "",
        "V": 0
}
{
        "ClassName":"TObj",
        "E": "meFirst",
        "K": "",
        "V": 0
}

Last edited by ComingNine (2018-07-30 14:54:32)

Offline

#3 2018-07-30 15:53:54

ComingNine
Member
Registered: 2010-07-29
Posts: 294

Re: How to serialize record with enum property ?

From your documentation , it seems that the solution is to switch from text-based serialization and deserialization to callback-based ones. big_smile Sorry for the trouble.

Offline

#4 2018-07-30 16:45:26

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

Re: How to serialize record with enum property ?

No need to write manual serialization using callbacks. big_smile

You can force enum serialization as text setting the woEnumSetsAsText or twoEnumSetsAsTextInRecord options.

Offline

#5 2018-07-30 17:21:05

ComingNine
Member
Registered: 2010-07-29
Posts: 294

Re: How to serialize record with enum property ?

Dear ab, many thanks !


Could you be kind enough to comment where these text settings you mentioned, i.e., woEnumSetsAsText or twoEnumSetsAsTextInRecord, can be applied to force enum serialization as text, for example, in the gist sample ? I mean, switching from

 (RecordSaveJSON(Rec, TypeInfo(TRec))); 

to

 (RecordSaveJSON(Rec, TypeInfo(TRec), True)); 

does not work.

Last edited by ComingNine (2018-07-30 17:22:56)

Offline

Board footer

Powered by FluxBB