2

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;
Jan Doggen
  • 8,799
  • 13
  • 70
  • 144
user299323
  • 55
  • 2
  • 8

2 Answers2

14

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.
Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
  • The SuperObject help file has this exact example (maybe not same code but same concept with RTTI) – Jerry Dodge Mar 15 '13 at 15:34
  • @JerryDodge Maybe because this is the way to go? If this case is documented, why should it be different? – Sir Rufo Mar 15 '13 at 15:56
  • 2
    I didn't say it should be different, I was just saying that because OP could have simply read SuperObject's help file which comes with the library rather than asking here. Exact same solution is already explained there. – Jerry Dodge Mar 15 '13 at 16:08
  • @JerryDodge +1 Sorry for misinterpreting your comment, but that fits to some question ;o) – Sir Rufo Mar 15 '13 at 16:34
3

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.

Teun Pronk
  • 1,367
  • 12
  • 24
  • Just to note: The result `"MyArray": [{ "1": "Apple", "2": "Orange"}` is **not** a valid JSON string. It should be `{"MyArray": [{ "1": "Apple", "2": "Orange"}]}` or even `[{ "1": "Apple", "2": "Orange"}]` – Sir Rufo Mar 19 '13 at 12:22