You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi中Spring4D集合JSON反序列化IList<T>(T为record)遇阻

解决Delphi中DelphiJSON反序列化JSON数组到Spring4D IList(T为record)的问题

问题背景

使用DelphiJSON处理默认泛型集合(如TList<T>)时序列化/反序列化正常,但无法直接将JSON数组反序列化为Spring4D的IList<T>接口类型(T为record),且不想退回使用TDataSet。

解决方案

DelphiJSON默认不支持Spring4D的接口式集合,需通过自定义反序列化器扩展类型支持,核心思路是利用Spring4D的具体实现类(如TList<T>)实例化IList<T>,并逐个反序列化JSON数组元素添加到集合中。

1. 实现泛型反序列化器

创建针对IList<T>的泛型反序列化器类,继承自DelphiJSON的TJSONDeserializer<IList<T>>:

uses
  DelphiJSON, Spring.Collections, System.JSON;

type
  TSpringIListDeserializer<T> = class(TJSONDeserializer<IList<T>>)
  protected
    function DoDeserialize(const AValue: TJSONValue; const AContext: TJSONContext): IList<T>; override;
  end;

function TSpringIListDeserializer<T>.DoDeserialize(const AValue: TJSONValue; const AContext: TJSONContext): IList<T>;
var
  LJSONArray: TJSONArray;
  LItemValue: TJSONValue;
  LItem: T;
begin
  // 用Spring4D的TList<T>实例化IList<T>接口
  Result := TList<T>.Create;
  if AValue is TJSONArray then
  begin
    LJSONArray := TJSONArray(AValue);
    // 遍历JSON数组,逐个反序列化元素并添加到集合
    for LItemValue in LJSONArray do
    begin
      LItem := DelphiJSON<T>.Deserialize(LItemValue, AContext.Settings);
      Result.Add(LItem);
    end;
  end;
end;

2. 注册反序列化器

在程序初始化阶段(如initialization块),为你的record类型对应的IList<T>注册上述反序列化器:

initialization
  // 替换TMyRecord为你的实际record类型
  DelphiJSON.RegisterDeserializer<IList<TMyRecord>>(TSpringIListDeserializer<TMyRecord>.Create);

3. 直接反序列化使用

完成注册后,即可像使用默认泛型集合一样直接反序列化为IList<T>:

result.Data := DelphiJSON<IList<TMyRecord>>.Deserialize(response.Content, jsonSetting);

扩展说明

如果需要支持Spring4D的其他集合接口(如ISet<T>、IEnumerable<T>),可参照上述逻辑,替换对应的实现类(如THashSet<T>)编写反序列化器并注册即可。

内容的提问来源于stack exchange,提问作者Edward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 00:14:59