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

Delphi 10 Seattle如何解析JSON属性中的字符串数组

Delphi 10 Seattle 解析JSON中字符串数组字段方案

Delphi 10 Seattle 内置了System.JSON单元,无需依赖第三方库即可完成解析,操作步骤如下:

  1. 引入依赖单元
    在代码的uses列表中添加System.JSON,如果需要用到异常处理、字符串列表类,可按需引入System.SysUtils、System.Classes。
  2. 核心解析逻辑
  • 先将原始JSON字符串解析为根级TJSONObject对象
  • 校验languages字段是否存在、是否为数组类型,避免强转错误
  • 将字段值转为TJSONArray类型,遍历数组取出每个元素的字符串值,存入目标数组/字符串列表即可

完整可运行示例代码:

uses
  System.SysUtils, System.JSON;

procedure ParseLanguageField;
var
  RawJson: string;
  RootJson: TJSONObject;
  LangArray: TJSONArray;
  LangArrResult: TArray<string>;
  Idx: Integer;
begin
  RawJson := '{"name":"Joe","age":45,"languages":["c++", "java", "cobol"]}';

  // 解析根对象,解析失败会返回nil
  RootJson := TJSONObject.ParseJSONValue(RawJson) as TJSONObject;
  if not Assigned(RootJson) then
    raise Exception.Create('JSON格式不合法');
  try
    // 校验字段类型
    if not (RootJson.GetValue('languages') is TJSONArray) then
      raise Exception.Create('languages字段不是预期的数组类型');
    LangArray := RootJson.GetValue<TJSONArray>('languages');

    // 组装字符串数组结果
    SetLength(LangArrResult, LangArray.Count);
    for Idx := 0 to LangArray.Count - 1 do
    begin
      LangArrResult[Idx] := LangArray.Items[Idx].Value;
    end;

    // 此处可自行使用LangArrResult做后续业务处理
  finally
    RootJson.Free;
    // 注意:LangArray及数组内元素无需手动释放,内存由根对象统一管理,手动释放会触发重复释放异常
  end;
end;

补充说明

  • 如果需要将结果存入TStringList等TStrings派生类,直接遍历LangArray,逐个调用Add(LangArray.Items[Idx].Value)即可。
  • 若JSON结构可能存在字段缺失的情况,可先调用RootJson.TryGetValue<TJSONArray>('languages', LangArray)做安全取值,避免抛出异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.20 16:15:51