Recent

Author Topic: How to create a function to convert a generic TFPGObjectList into a TJsonArray?  (Read 476 times)

LeoBruno

  • Jr. Member
  • **
  • Posts: 61
I'm new to fpc Lazarus and came from Delphi BackGround.

I need to create a method in order to convert Generic Object Lists into TJsonArray.

Delphi has it natively, but aparently FPC Lazarus doesn't.

Here is what I have:

Code: Pascal  [Select][+][-]
  1. generic class function TDAOJsonUtils.ObjectListToJsonArray<T>(aObjectList: T): TJsonArray;
  2. var
  3.   I: Integer;
  4.   _JsonStr: TJSONStreamer;
  5.   _JsonObj: TJsonObject;
  6. begin
  7.   result := TJsonArray.Create;
  8.   _JsonStr := TJSONStreamer.Create(nil);
  9.   try
  10.       for i := 0 to Pred(TFPGObjectList(aObjectList).Count) do
  11.     begin
  12.       _JsonObj := TJsonObject.Create;
  13.  
  14.         end;
  15.     finally
  16.     FreeAndNil(_JsonStr);
  17.     end;
  18. end;
  19.  
  20.  

It doesn't compile with and throw the following message at the "for loop" statement:

"generics without specialization cannot be used as a type for a variable"

Any tips?

Thank's in advance.
« Last Edit: July 25, 2022, 11:08:30 pm by LeoBruno »
Lazarus 2.2.2 FPC 3.2.2 Windows (qt5) Anchor Docking

Thaddy

  • Hero Member
  • *****
  • Posts: 11928
If you are coming from Delphi use generics.collections instead of FGL. It is 99% compatible and also included in the standard distro.
« Last Edit: July 24, 2022, 02:56:39 pm by Thaddy »
Black themes should be banned.

bytebites

  • Hero Member
  • *****
  • Posts: 505
You need to use switch {$mode delphi}

Thaddy

  • Hero Member
  • *****
  • Posts: 11928
No. generics.collections is already  compiled in delphi mode and can be used in mode objfpc too.
Modes are unit scope, not program scope.
« Last Edit: July 24, 2022, 07:41:26 pm by Thaddy »
Black themes should be banned.

PascalDragon

  • Hero Member
  • *****
  • Posts: 4562
  • Compiler Developer
Any tips?

  • Please use [ code=pascal ][ /code ] tags (without the spaces), making the code clearer to read and also avoids the forum software potentially cutting stuff
  • You need to specialize your TFPGObjectList<> (or your TObjectList<> if you follow Thaddy's suggestion of using Generics.Collections) in your cast with the type you intend, cause the compiler can't know what you're trying to do otherwise. So use specialize TFPGObjectList<T>() or whatever is the correct type; you could also make sure that your parameter is already typed correctly by declaring it as TFPGObjectList<T> instead of T for example.

 

TinyPortal © 2005-2018