Forum > General

How to create a function to convert a generic TFPGObjectList into a TJsonArray?


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  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---generic class function TDAOJsonUtils.ObjectListToJsonArray<T>(aObjectList: T): TJsonArray;var  I: Integer;  _JsonStr: TJSONStreamer;  _JsonObj: TJsonObject;begin  result := TJsonArray.Create;  _JsonStr := TJSONStreamer.Create(nil);  try      for i := 0 to Pred(TFPGObjectList(aObjectList).Count) do    begin      _JsonObj := TJsonObject.Create;         end;    finally    FreeAndNil(_JsonStr);    end;end;   
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.

If you are coming from Delphi use generics.collections instead of FGL. It is 99% compatible and also included in the standard distro.

You need to use switch {$mode delphi}

No. generics.collections is already  compiled in delphi mode and can be used in mode objfpc too.
Modes are unit scope, not program scope.


--- Quote from: LeoBruno on July 24, 2022, 02:15:11 pm ---Any tips?

--- End quote ---

* 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.



[0] Message Index

Go to full version