Trouble converting delphi objects with arrays to json -


i've been trying translate objects json string tjson.objecttojsonstring(object). works fine simple objects break if object contains array(static or dynamic). what's correct way of creating json string of object? i've looked @ tsuperobject wasn't apparent need do.

class structure

tperson = class(tobject) private   fid       : integer;   flastname : string;   ffirstname: string;   femail    : string;   fmyarray : array[0..2] of boolean;    function readarray(i : integer):boolean;   procedure writearray(i : integer; val:boolean); public   property id       : integer read fid        write fid;   property lastname : string  read flastname  write flastname;   property firstname: string  read ffirstname write ffirstname;   property email    : string  read femail     write femail;   property myarray[i : integer] :boolean read readarray write writearray; end; 

example

  person := tperson.create();   person.id := 25;   person.firstname := 'homer';   person.lastname  := 'bologna';   person.email := 'homer@bologna.com';    person.myarray[0] := true;   person.myarray[1] := false;   person.myarray[2] := true;    str := tjson.objecttojsonstring(person);//access violation 

you can persuade objecttojsonstring handle arrays, need arrays type info. array uses inline type, , not have type info.

for instance declare field fmyarray this:

type   tperson = class(tobject)   private     type       tbooleanarray = array [0 .. 2] of boolean;   private     fid: integer;     flastname: string;     ffirstname: string;     femail: string;     fmyarray: tbooleanarray; // <-- type has type info      function readarray(i: integer): boolean;     procedure writearray(i: integer; val: boolean);   public     property id: integer read fid write fid;     property lastname: string read flastname write flastname;     property firstname: string read ffirstname write ffirstname;     property email: string read femail write femail;     property myarray[i: integer]: boolean read readarray write writearray;   end; 

a call objecttojsonstring produces this:

 {"id":0,"lastname":"","firstname":"","email":"","myarray":[false,false,false]} 

likewise, dynamic arrays use

fmyarray: tarray<boolean>; 

rather than

fmyarray: array of boolean; 

for exact same reason.

you might want consider using different json library though. embarcadero supplied library doesn't have best of reputations.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -