Delphi如何遍历无方括号包裹的非数组类型JSON数据?
解决方案
你遇到的是标准的JSON对象(键值对集合)结构,不需要转数组,直接遍历JSON对象的键值对即可,代码逻辑和你之前遍历数组的写法高度相似,改动很小:
核心思路
data 字段是 TJSONObject 类型而非 TJSONArray,直接遍历该对象的 Pairs 集合,每一个Pair的JsonValue就是对应交易对的详情对象。
完整代码示例
uses System.JSON; ... var RootJson: TJSONValue; DataObject: TJSONObject; JsonPair: TJSONPair; TradingPairInfo: TJSONObject; tempName, tempPricingName: string; begin // 此处假设RootJson是你已经解析完成的接口返回JSON根对象 // 先取出data字段的JSON对象 DataObject := RootJson.GetValue<TJSONObject>('data'); if not Assigned(DataObject) then Exit; // 遍历所有键值对 for JsonPair in DataObject do begin // 可选:直接取外层键名,比如"KAVAUSDT" // Writeln('当前交易对键名:', JsonPair.Key); // 取当前交易对的详情对象,加类型判断避免异常 if not (JsonPair.JsonValue is TJSONObject) then Continue; TradingPairInfo := TJSONObject(JsonPair.JsonValue); // 后续取值逻辑和你之前处理数组元素的逻辑完全一致 tempName := TradingPairInfo.GetValue<string>('name'); tempPricingName := TradingPairInfo.GetValue<string>('pricing_name'); // 其他字段取值、业务逻辑处理 // ... end; end;
兼容低版本Delphi的写法
如果你使用的是不支持泛型GetValue方法的旧版本Delphi,可以改用如下写法取值:
// 取data对象 DataObject := RootJson.FindValue('data') as TJSONObject; // 取字段值 tempName := TradingPairInfo.Get('name').JsonValue.Value;
内容的提问来源于stack exchange,提问作者Abdullah Yılmaz
相关产品推荐
相关产品推荐

