In our project in Delphi XE 10.2.2, there are tons of records with short string fields.
The problem is that, when we use TJsonSerializer
from the System.JSON.Serializers
unit, those fields are ignored.
How can records with short strings be serialized to JSON?
With AnsiString
and String
fields, it works fine for sure. The problem is that, like I said before, there are a lot of existing records with short strings.
For example:
type
TTestRec = record
ShortStrData: string[50];
end;
procedure TForm1.Button1Click(Sender: TObject);
var
oSerializer: TJsonSerializer;
r: TTestRec;
begin
r.ShortStrData := 'short string text';
oSerializer := TJsonSerializer.Create;
try
Memo1.Text := oSerializer.Serialize(r);
finally
oSerializer.Free;
end;
end;
The result is:
{}
If we replace string[50]
with AnsiString
, the result is as expected:
{"ShortStrData":"short string text"}
I assume the problem is in the RTTI, but I'm not sure how to avoid/fix that.
CodePudding user response:
Indeed, some Object Pascal types (like ShortString and Real48) are not supported by the type information generator. Probably that is related to Delphi classes and objects, like it is mentioned in the documentation:
- In the visibility of class members, any real type except "Real48" can be published.
- "ShortString" is not among the automatable types.
As a consequence, RTTI-based features will not handle those types correctly, like your case with the JSON serializer (which is based on RTTI) that won't serialize fields in those types.
For your problem with "ShortString", you can solve it through a workaround by defining your own string type (and use it in your record later), like this:
type
string50 = string[50];
TTestRec = record
ShortStrData: string50;
end;.
But keep in mind that those types are maintained for backward compatibility, especially the "ShortString" which is not supported by mobile compilers, so you have to consider migrating your code base to the newest Object Pascal/Delphi versions.