1. 项目概述:为什么需要这个JSON封装库?
在Delphi开发中处理JSON数据一直是个痛点。虽然从Delphi 10 Seattle开始引入了System.JSON单元,但原生API设计过于底层,用起来总有种"杀鸡用牛刀"的感觉。每次都要写一堆GetValue、TryGetValue,处理嵌套结构时更是要层层判断,代码可读性直线下降。
这个封装库的诞生源于我最近接的一个物联网项目。设备上报的JSON数据结构复杂,包含多层嵌套的传感器数据。当我第20次写下if not json.GetValue('data').TryGetValue('sensors') then时,终于忍无可忍决定自己造轮子。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 核心设计思路
2.1 基于System.JSON的轻量封装
选择基于System.JSON而不是第三方库有几个考虑:
- 兼容性:System.JSON是Delphi自带单元,从XE8到最新版都可用
- 性能:直接使用原生TJSONObject/TJSONArray,没有额外解析开销
- 无依赖:不需要引入第三方dll或bpl
delphi复制type
TJsonHelper = class helper for TJSONObject
function GetString(const Path: string; Default: string = ''): string;
function GetInteger(const Path: string; Default: Integer = 0): Integer;
// 其他类型方法...
end;
2.2 路径式访问设计
最大的创新点是引入了路径式访问语法。比如要获取{"data":{"user":{"name":"张三"}}}中的姓名,传统写法需要三层判断,现在只需要:
delphi复制UserName := Json.GetString('data.user.name');
实现原理是利用字符串分割和递归查找:
delphi复制function TJsonHelper.GetValueByPath(const Path: string): TJSONValue;
var
Segments: TArray<string>;
Current: TJSONValue;
I: Integer;
begin
Segments := Path.Split(['.']);
Current := Self;
for I := 0 to High(Segments) do
begin
if not (Current is TJSONObject) then Exit(nil);
Current := TJSONObject(Current).GetValue(Segments[I]);
if Current = nil then Exit(nil);
end;
Result := Current;
end;
3. 关键功能实现细节
3.1 类型安全访问方法
为了避免类型转换错误,为每种基础类型都提供了专用方法:
delphi复制function TJsonHelper.GetBoolean(const Path: string; Default: Boolean): Boolean;
var
Va
