1. 项目概述:Delphi JSON封装库的设计初衷
在Delphi开发中,处理JSON数据一直是个既基础又麻烦的工作。虽然System.JSON单元提供了基础功能,但原生API用起来实在不够优雅。每次都要写一堆GetValue、TryGetValue,处理嵌套结构时更是要层层判断,代码又长又难维护。
这个封装库就是为了解决这些痛点而生的。它基于Delphi原生的System.JSON单元构建,但提供了更符合人类思维的链式调用接口。举个例子,原来要取个深层值得这么写:
delphi复制var
JsonObj: TJSONObject;
begin
JsonObj := TJSONObject.ParseJSONValue(JsonString) as TJSONObject;
if Assigned(JsonObj) then
try
if JsonObj.TryGetValue('user', userObj) then
if userObj.TryGetValue('address', addressObj) then
if addressObj.TryGetValue('city', cityValue) then
ShowMessage(cityValue.Value);
finally
JsonObj.Free;
end;
end;
用了封装库后,一行搞定:
delphi复制ShowMessage(TJsonHelper.Parse(JsonString).Path('user.address.city').AsString);
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 核心功能设计
2.1 链式调用接口
这个库最核心的设计理念就是链式调用(Fluent Interface)。我们封装了一个TJsonHelper类,所有方法都返回自身实例,这样就可以像搭积木一样把操作串联起来。
关键实现要点:
- 每个方法都返回Self,保持链式调用
- 内部维护一个FCurrentValue指针,指向当前操作的JSON节点
- 每次操作后自动更新FCurrentValue
- 支持nil安全,任何一步出错都不会报错而是返回空值
典型用法示例:
delphi复制TJsonHelper
.Parse(JsonString) // 解析JSON字符串
.Path('user.address') // 导航到address节点
.Field('city').AsString; // 获取city字段值
2.2 智能类型转换
原生System.JSON需要手动处理类型转换,这个封装库内置了智能转换逻辑:
delphi复制// 自动处理各种类型转换
.AsString // 转为字符串
.AsInteger // 转为整数
.AsBoolean // 转为布尔值
.AsDouble // 转为浮点数
.AsDateTime // 转为日期时间(支持ISO8601格式)
.AsArray // 转为数组迭代器
特别的是.AsDateTime实现:
delphi复制function TJsonHelper.AsDateTime: TDateTime;
begin
if FCurrentValue is TJSONString then
Result := ISO8601ToDate(FCurrentValue.Value)
else if FCurrentValue is TJSONNumber then
Result := UnixToDateTime(FCurrentValue.AsInt64)
else
Result := 0;
end;
