Delphi 2007中将JSON字符串数组转换为TStringList的实现方法
在Delphi 2007中解析JSON字符串数组为TStringList
由于Delphi 2007没有内置JSON处理单元,我们可以通过手动处理字符串的方式,将["Ford", "BMW", "Fiat"]这类JSON字符串数组转换为TStringList对象。以下是具体实现方案:
实现代码
核心解析函数
function ParseJSONStringArray(const AJSON: string): TStringList; var LCleanedStr: string; LItems: TStringList; I: Integer; LItem: string; begin Result := TStringList.Create; try // 清理原始字符串:去除前后空白,检查首尾是否为[] LCleanedStr := Trim(AJSON); if (Length(LCleanedStr) < 2) or (LCleanedStr[1] <> '[') or (LCleanedStr[Length(LCleanedStr)] <> ']') then Exit; // 移除首尾的[],再次清理空白 LCleanedStr := Copy(LCleanedStr, 2, Length(LCleanedStr) - 2); LCleanedStr := Trim(LCleanedStr); // 空数组直接返回空列表 if LCleanedStr = '' then Exit; // 按逗号分割元素 LItems := TStringList.Create; try LItems.Delimiter := ','; LItems.StrictDelimiter := True; LItems.DelimitedText := LCleanedStr; // 逐个处理元素:去除引号和多余空白 for I := 0 to LItems.Count - 1 do begin LItem := Trim(LItems[I]); // 移除首尾的双引号 if (Length(LItem) >= 2) and (LItem[1] = '"') and (LItem[Length(LItem)] = '"') then LItem := Copy(LItem, 2, Length(LItem) - 2); LItem := Trim(LItem); // 忽略空元素 if LItem <> '' then Result.Add(LItem); end; finally LItems.Free; end; except Result.Free; raise; end; end;
使用示例
var LJSONStr: string; LStringList: TStringList; begin LJSONStr := '["Ford", "BMW", "Fiat"]'; LStringList := ParseJSONStringArray(LJSONStr); try // 示例:输出所有元素 ShowMessage(LStringList.Text); finally LStringList.Free; end; end;
补充说明
- 该实现适用于简单场景:元素为普通字符串,内部不包含逗号、转义双引号(如
"a,b"或"He said \"Hi\"")等特殊内容。 - 如果需要处理复杂JSON字符串数组,可扩展代码逻辑手动扫描处理转义字符,或引入兼容Delphi 2007的第三方JSON解析库。
内容的提问来源于stack exchange,提问作者Allan F
相关产品推荐
相关产品推荐

