#1 2020-07-18 15:54:20

Hafedh TRIMECHE
Member
Registered: 2016-09-18
Posts: 32

RecordLoadJSON & soReadIgnoreUnknownFields Boolean problem

Varsion: 1.18.6089
When a Boolean value not initialized (not exists in the Json document), the returned value is always set to True.
The problem is solved only if the variable is set to its default value using Data := default(T) before invoking RecordLoadJSON

class function _J_.Decode<T>(Text:string;out Data:T):Boolean;
var
  RttiInfo : Pointer;
begin
  while (Text<>'') and (Text[Length(Text)]<>'}') do SetLength(Text,Length(Text)-1);
  if Text='' then
  begin
    Data := default(T);
    Exit(False);
  end;
  RttiInfo := TypeInfo(T);
  try
    TTextWriter.RegisterCustomJSONSerializerSetOptions(RttiInfo,[soReadIgnoreUnknownFields],True);
    Result := RecordLoadJSON(Data,RawUTF8(Text),RttiInfo);
  except
    Result := False;
  end;
  if (not Result) then Data := default(T);
end;

the modified function:

class function _J_.Decode<T>(Text:string;out Data:T):Boolean;
var
  RttiInfo : Pointer;
begin
  Data := default(T);
  while (Text<>'') and (Text[Length(Text)]<>'}') do SetLength(Text,Length(Text)-1);
  if Text='' then Exit(False);
  RttiInfo := TypeInfo(T);
  try
    TTextWriter.RegisterCustomJSONSerializerSetOptions(RttiInfo,[soReadIgnoreUnknownFields],True);
    Result := RecordLoadJSON(Data,RawUTF8(Text),RttiInfo);
  except
    Result := False;
  end;
  if (not Result) then Data := default(T);
end;

Offline

#2 2020-07-18 22:39:10

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

Re: RecordLoadJSON & soReadIgnoreUnknownFields Boolean problem

It is as designed.

Unknown fields are ignored, not set to their default value. This is what soReadIgnoreUnknownFields stand for.
The caller has to reset the value before RecordLoadJSON(), if needed.

It is useful in some cases, e.g. if you want to update the fields, not fill all of them.
And filling a record with zeros before unserialization is faster than managing individual fields.

Offline

Board footer

Powered by FluxBB