#1 2016-02-26 21:58:08

avista
Member
Registered: 2014-01-06
Posts: 63

JSON Default Serialization Options

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

#2 2016-02-27 10:27:14

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

Re: JSON Default Serialization Options

This would break how options are expected to work.

Sometimes, you just disable some options on purpose.
With your patch, it would enable those options...

Offline

#3 2016-02-27 16:35:08

avista
Member
Registered: 2014-01-06
Posts: 63

Re: JSON Default Serialization Options

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

Board footer

Powered by FluxBB