Delphi 10.1中如何遍历JSON值并按地区分类提取银行假日数据
Delphi 10.1 遍历英国政府银行假日JSON数据示例代码
假设你已经通过TRESTClient和TRESTRequest成功获取到JSON响应数据,以下是遍历解析JSON并按要求输出的示例代码:
uses System.JSON, System.SysUtils; procedure ParseUKBankHolidays(const JSONContent: string); var RootObj: TJSONObject; RegionPair: TJSONPair; RegionData: TJSONObject; EventsArray: TJSONArray; EventItem: TJSONObject; RegionName: string; Title, EventDate, Notes: string; Bunting: Boolean; begin try // 将JSON字符串解析为根对象 RootObj := TJSONObject.ParseJSONValue(JSONContent) as TJSONObject; if not Assigned(RootObj) then Exit; try // 遍历所有地区节点 for RegionPair in RootObj do begin RegionName := RegionPair.JsonString.Value; Writeln('地区名称: ', RegionName); Writeln('------------------------'); // 获取当前地区的数据对象 RegionData := RegionPair.JsonValue as TJSONObject; // 获取events数组 EventsArray := RegionData.GetValue<TJSONArray>('events'); if not Assigned(EventsArray) then Continue; // 遍历每个假日事件 for EventItem in EventsArray do begin // 提取各字段值,处理字段可能不存在的情况 EventItem.TryGetValue<string>('title', Title); EventItem.TryGetValue<string>('date', EventDate); EventItem.TryGetValue<string>('notes', Notes); // bunting是布尔类型,默认设为False if not EventItem.TryGetValue<Boolean>('bunting', Bunting) then Bunting := False; // 输出字段内容 Writeln('标题: ', Title); Writeln('日期: ', EventDate); Writeln('备注: ', IfThen(Notes.IsEmpty, '无', Notes)); Writeln('是否悬挂彩旗: ', IfThen(Bunting, '是', '否')); Writeln('------------------------'); end; Writeln; end; finally RootObj.Free; end; except on E: Exception do Writeln('解析错误: ', E.Message); end; end; // 调用示例(假设你已从REST请求中拿到Response.Content) // ParseUKBankHolidays(RESTRequest.Response.Content);
输出示例
地区名称: England and Wales
标题: New Year’s Day
日期: 2024-01-01
备注: 无
是否悬挂彩旗: 是标题: Good Friday
日期: 2024-03-29
备注: 无
是否悬挂彩旗: 否地区名称: Scotland
标题: New Year’s Day
日期: 2024-01-01
备注: 无
是否悬挂彩旗: 是
说明
- 代码中使用
TryGetValue方法安全提取字段,避免因JSON字段缺失导致程序崩溃 - 对
notes字段做了空值处理,显示"无"替代空字符串 bunting字段默认设为False,确保字段不存在时也有合理输出
内容的提问来源于stack exchange,提问作者Yuppski
相关产品推荐
相关产品推荐

