#1 2024-06-28 05:12:05

bigheart
Member
Registered: 2014-08-01
Posts: 53

DynArray.LoadFromJson not working

Hello.

Please review below code: Delphi XE5, windows10, latest version mormot2

  LJson := '[{"Task":12,"PO":"aa"},{"Task":12,"PO":"bb"}]';
  LDynArr.Init(TypeInfo(TRawUTF8DynArray), LDynUtf8);
  LDynArr.LoadFromJson(PUTF8Char(LJson));
  Check(LDynArr.Count > 0) ==> count is 0

Give me some advice.

Last edited by bigheart (2024-06-28 05:16:18)

Offline

#2 2024-06-28 06:09:24

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

Re: DynArray.LoadFromJson not working

Hello!

This is as expected.

You define a TRawUTF8DynArray which expects... a raw of JSON strings ["a',"b","c"] and you give to it a raw of JSON objects.
Therefore, LoadFromJson() fails.

Two remarks:
1) always check the result of functions, here the result of LoadFromJson()
2) there are two overloaded LoadFromJson() functions: you force to use the one with PUtf8Char() which parse and modify the content in place so your code will probably GPF with such a constant input string - so you need to use the overloaded function which uses a RawUtf8 as input (if you don't know much about pointers don't use them)

Offline

#3 2024-06-28 08:00:36

bigheart
Member
Registered: 2014-08-01
Posts: 53

Re: DynArray.LoadFromJson not working

Thanx ab.

Then, to use the TDynArray with JSON Objects, how to set the init function?

  LDynArr.LoadFromJSON(LUtf8); ==> LDynArr.Count = 0
--------------------------------------------------------------------------
  LDynArr.Init(TypeInfo(TVariantDynArray), LDynUtf8);
  LDynArr.LoadFromJSON(LUtf8); ==> still LDynArr.Count = 0

Is there any option to use JSON Object Array using TDynArray feature?

Offline

#4 2024-06-28 08:21:06

bigheart
Member
Registered: 2014-08-01
Posts: 53

Re: DynArray.LoadFromJson not working

OK.

I can use the   IDocList;

    LDocList: IDocList;
   
    LDocList := DocList(LUtf8);
    LDocList.Len; // = 2

Offline

#5 2024-06-28 09:26:56

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

Re: DynArray.LoadFromJson not working

IDocList / IDocDict are indeed the way to go if you are not very sure about what you are doing.

With TDynArray you could define

type
  TMyRec = packed record
    Task: integer;
    PO: string;
  end;
  TMyRecs = array of TMyRec;
...
  LDynArr.Init(TypeInfo(TMyRecs), LDynMyRec);

Offline

Board footer

Powered by FluxBB