#1 2022-09-04 08:44:08

radexpol
Member
From: Poland, Krk
Registered: 2019-11-29
Posts: 116

Access violation DynArrayLoadJSON

type
  TRec = packed record
    firstname: string;
  end;

procedure Test;
var
  r: TRec;
  ar: TArray<TRec>;
  x: RawUtf8;
begin
  r.firstname := 'sdf';
  ar := ar + [r];
  DynArrayLoadJSON(ar, UniqueRawUTF8(x),  TypeInfo(TArray<TRec>));  -> access violation

An error occured in line:
Ctxt.Json := GotoNextNotSpace(Ctxt.Json);  -> Ctxt.Json is nil
in method:
_JL_DynArray

Offline

#2 2022-09-04 08:53:23

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,655
Website

Re: Access violation DynArrayLoadJSON

On which compiler ?

Your code is not correct.
Did you mean DynArraySaveJson()?

Offline

#3 2022-09-04 10:10:09

radexpol
Member
From: Poland, Krk
Registered: 2019-11-29
Posts: 116

Re: Access violation DynArrayLoadJSON

I'm using 10.4.

I want to convert json into array of TRec structure, something like TJson.JsonToObject<TPerson>(Memo1.Lines.Text);

Offline

#4 2022-09-04 19:10:58

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,655
Website

Re: Access violation DynArrayLoadJSON

Your code is not correct because x is '' so no valid JSON.

Offline

#5 2022-09-04 19:41:02

radexpol
Member
From: Poland, Krk
Registered: 2019-11-29
Posts: 116

Re: Access violation DynArrayLoadJSON

  var 
     x: UTF8String;  
     r: TRec;
     ar: TArray<TRec>;
  begin
    r.firstname := 'ssss';
    ar := ar + [r];
    x := '[]';

    DynArrayLoadJSON(ar, UniqueRawUTF8(x),  TypeInfo(TArray<TRec>));

    ShowMessage(x);

it does not raise AV but the x does not contain any data, just empty array as initialized

Offline

#6 2022-09-04 21:32:10

tbo
Member
Registered: 2015-04-20
Posts: 353

Re: Access violation DynArrayLoadJSON

Try it as follows:

type
  TRec = packed record
    firstName: String;
  end;

  TRecDynArray = array of TRec;

var
  json: RawJson;
  recs: TRecDynArray;
begin
  json := '[{"firstName": "one"}, {"firstName": "two"}, {"firstName": "three"}]';
  if DynArrayLoadJson(recs, json, TypeInfo(TRecDynArray)) then
    ShowMessage(recs[1].firstName);

Or if I read your post again, you may need the following:

var
  recs: TRecDynArray;
begin
  SetLength(recs, 3);
  recs[0].firstName := 'one';
  recs[1].firstName := 'two';
  recs[2].firstName := 'three';
  ShowMessage(Utf8ToString(DynArraySaveJson(recs, TypeInfo(TRecDynArray))));

With best regards
Thomas

Last edited by tbo (2022-09-04 21:43:08)

Offline

#7 2022-09-04 22:10:17

radexpol
Member
From: Poland, Krk
Registered: 2019-11-29
Posts: 116

Re: Access violation DynArrayLoadJSON

Thank you, the:
ShowMessage(Utf8ToString(DynArraySaveJson(ar, TypeInfo(TArray<TRec>))));
also is OK.

Offline

Board footer

Powered by FluxBB