JSON library for Serialisation/Deserialization of Spring4D collections?

36 views
Skip to first unread message

rosch

unread,
May 28, 2024, 12:28:19 PMMay 28
to Spring4D
I am looking for a library which enables me to serialise/deserialize Spring4D collections (e.g. IList<T> or IDictionary<TKey, TValue> as JSON. If there is no library currently implementing Spring collections, which one would you recommend to extend?

Rick Wheeler

unread,
May 28, 2024, 5:37:59 PMMay 28
to Spring4D
Personally, I've just extended the in-built Delphi classes into a generic class that can handle my IList needs. Here's a code sample below:

function TJsonSerialiser<T>.ObjectListFromJsonString(const AJson: string): IList<T>;
var
  JsonArray: TJSONArray;
  JsonItem: TJSONValue;
  JsonObject: TJSONObject;//, JsonTarget: TJSONObject;
begin
  JsonObject := TJSONObject.ParseJSONValue(AJson) as TJSONObject;
  try
    Result := TCollections.CreateObjectList<T>;
    if JsonObject.TryGetValue<TJSONValue>('array', JsonArray) then
      for JsonItem in JsonArray do
        Result.Add(Self.ObjectFromJsonObject(JsonItem as TJSONObject));
  finally
    JsonObject.Free;
  end;
end;

function TJsonSerialiser<T>.ObjectListToJsonString(AList: IList<T>): string;
var
  JsonObject: TJSONObject;
  JsonArray: TJSONArray;
  Item: T;
begin
  JsonObject := TJsonObject.Create;
  try
    JsonArray := TJSONArray.Create;
    for Item in AList do
      JsonArray.AddElement(TJson.ObjectToJsonObject(Item));
    Result := JsonObject.ToJSON;
  finally
    JsonObject.Free;
  end;
end;

The TJsonSerialiser is a full class handling any non-standard Json stuff such as Nullable<> types etc as well. Not sure if this helps your needs, but suits our purposes without using 3rd party libraries.

Stefan Glienke

unread,
May 29, 2024, 7:40:41 AMMay 29
to Spring4D
https://github.com/mirko-bianco/FidoLib seems to support spring4d collections and also DMVC has some support though on both I don't know to what extent.
Generally, it should not be a big issue to support serialization of spring4d 2.0 collections - you just don't have to use RTTI but the non-generic interfaces that have been designed explicitly for that purpose.

Mainly that is the ICollection (non-generic) one. It internally creates a small non-generic wrapper that works with TValue for serialization and deserialization.

Reply all
Reply to author
Forward
0 new messages