#1 2014-05-05 22:06:07

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

RecordLoadJSON Bug - Modifies contents of JSON input parameter

It looks like there is a bug with RecordLoadJSON.

program JsonBug;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  SynCommons;

type
  TTestRec = packed record
    Id: Integer;
    Name: string;
  end;

const
  __TTestRec = 'Id: Integer; Name: string;';

var
  Rec: TTestRec;
  Json1, Json2: RawUTF8;
begin
  try
    Rec.Id := 55;
    Rec.Name := 'This is the name.';

    TTextWriter.RegisterCustomJSONSerializerFromText(TypeInfo(TTestRec), __TTestRec);
    Json1 := RecordSaveJSON(Rec, TypeInfo(TTestRec));

    Rec := Default(TTestRec);
    RecordLoadJSON(Rec, @Json1[1], TypeInfo(TTestRec));
    Json2 := RecordSaveJSON(Rec, TypeInfo(TTestRec));

    Assert(SameTextU(Json1, Json2));
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

The following assertion fails, because RecordSaveJSON modified the contents of the Json1 parameter:

Assert(SameTextU(Json1, Json2));

Json1 BEFORE call to RecordLoadJSON:

  '{"Id":55,"Name":"This is the name."}' 

Json1 AFTER call to RecordLoadJSON: 

  '{"Id'#0#0'55'#0'"Name'#0#0'"This is the name.'#0#0 

Offline

#2 2014-05-06 07:41:16

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

Re: RecordLoadJSON Bug - Modifies contents of JSON input parameter

This is not a bug, this is how the JSON parser works: it escapes in-place the JSON buffer, to minimize the allocated memory, and speed up the process.
See http://blog.synopse.info/post/2011/06/0 … ON-parsing
This is the same for TDynArray.LoadFromJSON(), VariantLoadJSON() and so on, as soon as you give a PUTF8Char.
The functions which accept a RawUTF8 do perform a temporary copy of the data before parsing.

It may be confusing, so I've just added a clear comment about it for RecordLoadJSON() function.
http://synopse.info/fossil/info/6c4beaaebc

Offline

#3 2014-05-06 07:47:27

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

Re: RecordLoadJSON Bug - Modifies contents of JSON input parameter

Thanks for the explanation, that clears it up. smile

Offline

Board footer

Powered by FluxBB