Jump to content
Bart Verbakel

Unable to write array of integers to JSON

Recommended Posts

Hello,

 

I am trying to convert a record to a JSON string, so I can save and load the data to a file.

I have a record with several datatypes, but for some reason I am unable to write an array of integers to a JSON string.

Al other datatypes (array of string and booleans) work ok.

 

 

procedure TForm1.Button7Click(Sender: TObject);
type TMyRecord=record
                Name:String;
                 Int:Array[1..3] of integer;
                 Str:Array[1..3] of string;
                end;
var MyRecord:TMyRecord;
var Serializer:TJsonSerializer;
begin
  MyRecord.name:='Bart';
  Myrecord.Int[1]:=9;
  Myrecord.Int[2]:=5;
  Myrecord.Int[3]:=23;
  Myrecord.Str[1]:='A';
  Myrecord.Str[2]:='B';
  Myrecord.Str[3]:='C';

  Serializer:=TJsonSerializer.Create;
  Memo1.Lines.Clear;
  Memo1.Lines.Add(serializer.Serialize(MyRecord));
  FreeAndNil(Serializer);

end;

 

The JSON output string is:

{"Name":"Bart","Str":["A","B","C"],"Rain":false}

 

Why am I missing the array 'Int' in this JSON string?

I also tried to use a different datatype iso integers (Int64, double, byte, real), but this does not work either.

 

With kind regards,

 

Bart

 

 

 

Share this post


Link to post
11 hours ago, Bart Verbakel said:

Why am I missing the array 'Int' in this JSON string?

The problem is simple. The way you have defined the field in the record, no Rtti information is created. This can be illustrated with the following:

var rttiType: TRttiType := TRttiContext.Create.GetType(TypeInfo(TMyRecord));
if rttiType <> Nil then
begin
  var recFieldType: TRttiType;
  for var field: TRttiField in rttiType.GetFields do
  begin
    recFieldType := field.FieldType;
    if recFieldType <> Nil then
      ShowMessage(recFieldType.ClassType.ClassName)
    else
      ShowMessage('Nil');
  end;
end;

Solution: Explicitly define your own type or use dynamic arrays.

type
  TInt3Array = array[1..3] of Integer;

With best regards

Thomas

  • Like 1

Share this post


Link to post
type
  TInt3Array = array[1..3] of Integer;

 

This is so simple...

For me both declarations are the same, so I never found this solution by myself.

 

Thank you for the support.

 

Bart

 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×