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

是否可声明值为TStringList数组的TObjectDictionary?JSON编辑器存储方案咨询

特定结构JSON编辑器内存存储结构方案

核心结论

你提到的带tag字符串字段+两个TStringList字段的动态数组方案完全可用,实现复杂度远低于你最初设想的嵌套TObjectDictionary方案,完全匹配你的业务需求。

动态数组方案实现细节

  • 首先定义轻量业务类存储单条意图数据:
unit IntentData;

interface

uses System.Classes;

type
  TIntentItem = class
  public
    /// <summary>对应JSON中的tag字段值</summary>
    TagName: string;
    /// <summary>存储patterns数组的所有字符串</summary>
    Patterns: TStringList;
    /// <summary>存储responses数组的所有字符串</summary>
    Responses: TStringList;
    constructor Create;
    destructor Destroy; override;
  end;

implementation

{ TIntentItem }

constructor TIntentItem.Create;
begin
  inherited;
  Patterns := TStringList.Create;
  Responses := TStringList.Create;
  // 配置换行分隔,可直接与TMemo.Lines双向赋值
  Patterns.LineBreak := #13#10;
  Responses.LineBreak := #13#10;
  Patterns.StrictDelimiter := True;
  Responses.StrictDelimiter := True;
end;

destructor TIntentItem.Destroy;
begin
  Responses.Free;
  Patterns.Free;
  inherited;
end;

end.
  • 用动态数组承载所有解析后的意图数据:
    // 窗体全局变量声明
    FIntentList: array of TIntentItem;
    
  • 数据切换逻辑:下拉框的ItemIndex直接对应动态数组下标,选中后直接将对应下标TIntentItem的Patterns赋值给Patterns输入框的Lines属性、Responses赋值给Responses输入框的Lines属性,切换时间复杂度为O(1),性能完全满足日常使用。
  • 保存回写JSON时直接遍历动态数组,按顺序写入intents数组即可,和原始JSON结构完全对齐。

备选优化方案(针对扩展需求)

如果后续需要支持tag重名校验、tag搜索定位等功能,可以改用TObjectDictionary实现,无需嵌套,复杂度和动态数组接近:

  • 引入System.Generics.Collections单元,声明字典变量:
    FIntentDict: TObjectDictionary<string, TIntentItem>;
    
  • 初始化时指定[doOwnsValues]参数,字典释放时会自动释放所有TIntentItem实例,无需手动管理内存。
  • 优势是可通过ContainsKey方法快速判断tag是否重复,通过键直接检索对应意图数据,不需要遍历数组。

选型建议

  • 无额外扩展需求、要求保持JSON原始intents顺序:优先选动态数组方案,代码量最少,实现最快。
  • 有tag重名校验、搜索需求:选TObjectDictionary方案,灵活度更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:24:00