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

如何检测空JSON对象?Delphi JsonDataObjects技术问题

解决方案:用JsonDataObjects处理cPanel API JSON数据

1. 检测空JSON对象{}

JsonDataObjects里,空对象{}是有效的TJsonObject实例而非null,因此直接用IsNull判断会失效。可通过两种方式检测:

  • 检查TJsonObject的Count属性:值为0则是空对象
  • 若版本支持,使用HasKeys方法:返回False表示无任何键值对

示例代码:

var
  MainObj, MetaObj: TJsonObject;
begin
  MainObj := TJsonObject.Parse('{"metadata": {}}') as TJsonObject;
  try
    MetaObj := MainObj['metadata'] as TJsonObject;
    if (MetaObj <> nil) and (MetaObj.Count = 0) then
      ShowMessage('metadata是空对象{}')
    else
      ShowMessage('metadata非空');
  finally
    MainObj.Free;
  end;
end;

2. 提取无键名的数据

JSON规范中对象必须包含键值对,你所说的“无键名数据”大概率是JSON数组(格式如["val1", "val2"]),或是键为数字索引的对象(格式如{"0": "val1", "1": "val2"}),分两种情况处理:

情况A:数据是JSON数组

若metadata是非空数组,转为TJsonArray后遍历元素即可:

var
  MainObj: TJsonObject;
  MetaArray: TJsonArray;
  I: Integer;
begin
  MainObj := TJsonObject.Parse('{"metadata": ["item1", "item2", "item3"]}') as TJsonObject;
  try
    if MainObj['metadata'].JsonType = jtArray then
    begin
      MetaArray := MainObj['metadata'] as TJsonArray;
      for I := 0 to MetaArray.Count - 1 do
        ShowMessage('元素' + IntToStr(I) + ': ' + MetaArray[I].AsString);
    end;
  finally
    MainObj.Free;
  end;
end;

情况B:数据是数字索引键的对象

若metadata是键为数字字符串的对象,直接遍历TJsonObject的Values集合获取所有值:

var
  MainObj, MetaObj: TJsonObject;
  Value: TJsonValue;
begin
  MainObj := TJsonObject.Parse('{"metadata": {"0": "item1", "1": "item2"}}') as TJsonObject;
  try
    MetaObj := MainObj['metadata'] as TJsonObject;
    if MetaObj.Count > 0 then
    begin
      for Value in MetaObj.Values do
        ShowMessage(Value.AsString);
    end;
  finally
    MainObj.Free;
  end;
end;

注意事项

  • 转换类型前务必先判断JsonType,避免类型转换错误:比如用MainObj['metadata'].JsonType区分jtObject和jtArray
  • 若cPanel API返回的metadata结构不确定,可先输出MainObj['metadata'].ToJSON查看实际格式,再针对性处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:42:56