You are not logged in.
Pages: 1
When defining JSON serialization options, I currently need to set the options for each record.
For example:
var
Options: TJSONCustomParserSerializationOptions;
begin
Options := [soReadIgnoreUnknownFields];
TTextWriter.RegisterCustomJSONSerializerSetOptions(TypeInfo(TRecord_1), Options, True);
TTextWriter.RegisterCustomJSONSerializerSetOptions(TypeInfo(TRecord_2), Options, True);
TTextWriter.RegisterCustomJSONSerializerSetOptions(TypeInfo(TRecord_3), Options, True);
end;
However, if I forget to register a new record, then I invariably run into parsing problems when the users of my REST service include unknown fields.
So, I created a singleton method to be able to specify default options:
var
Options: TJSONCustomParserSerializationOptions;
begin
Options := [soReadIgnoreUnknownFields];
TJSONRecordAbstract.SetDefaultSerializationOptions(Options);
end;
Would it be possible to include this in the official code? Here are my proposed changes:
var
DefaultTextWriterJSONClass: TTextWriterClass = TTextWriter;
DefaultTextWriterTrimEnum: boolean;
DefaultSerializationOptions: TJSONCustomParserSerializationOptions; //<----------
class procedure TJSONRecordAbstract.SetDefaultSerializationOptions(aOptions: TJSONCustomParserSerializationOptions);
begin
DefaultSerializationOptions := aOptions;
end;
function TJSONRecordAbstract.CustomReader(P: PUTF8Char; var aValue; out aValid: Boolean): PUTF8Char;
var Data: PByte;
begin
Data := @aValue;
fOptions := fOptions + DefaultSerializationOptions; //<-----------------
aValid := Root.ReadOneLevel(P,Data,Options);
result := P;
end;
procedure TJSONRecordAbstract.CustomWriter(const aWriter: TTextWriter; const aValue);
var P: PByte;
begin
P := @aValue;
fOptions := fOptions + DefaultSerializationOptions; //<-----------------
Root.WriteOneLevel(aWriter,P,Options);
end;
Perhaps there is a better/cleaner way to achieve this, but this was the only way I could find to get it to work.
Thanks
Offline
Fair enough.
If there's no straightforward way to achieve this then I guess I'll just continue registering every DTO in my project and will deal with the inevitable "PerThread execution failed (probably due to bad input parameters)" error on a case by case basis.
Offline
Pages: 1