user299323
user299323

Reputation: 55

Store Array of Record in JSON

How can an array of record be stored in JSON via SuperObject library. For example..

type
  TData = record
    str: string;
    int: Integer;
    bool: Boolean;
    flt: Double;
  end;

var
DataArray: Array[0..100] of TData;

Upvotes: 2

Views: 4199

Answers (2)

Sir Rufo
Sir Rufo

Reputation: 19106

Just use the superobject Marshalling TSuperRTTIContext

program Project1;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  superobject,
  System.SysUtils;

type
  TData = record
    str : string;
    int : Integer;
    bool : Boolean;
    flt : Double;
  end;

  TDataArray = Array [0 .. 100] of TData;

procedure Test;
var
  DataArray : TDataArray;
  so :        ISuperObject;
  ctx :       TSuperRttiContext;
begin
  ctx := TSuperRttiContext.Create;
  try
    so := ctx.AsJson<TDataArray>( DataArray );
  finally
    ctx.Free;
  end;
  Writeln( so.AsJson );
end;

begin
  try
    Test;
  except
    on E : Exception do
      Writeln( E.ClassName, ': ', E.Message );
  end;

  ReadLn;

end.

Upvotes: 14

Teun Pronk
Teun Pronk

Reputation: 1397

Make it a string first.

Your array:
//Array[0] := 'Apple';
//Array[1] := 'Orange';
//Array[2] := 'Banana';
myArrayAsStr := '"MyArray": [{ "1": "' + Array[0] +'", "2": "' + Array[1] +'"}';

Then you can just make it into JSON with SO(myArrayAsStr) You can always generate your array as string in a different procedure but I think thats the way to do it.

Ill keep checking if there is an easier way ;)

EDIT: SuperObject also has the following function: function SA(const Args: array of const): ISuperObject; overload; You will be able to convert that to a string again and add it in the total JSON string.

Upvotes: 3

Related Questions