gpt4 book ai didi

使用 Delphi Xe5 将 JSON 转为 StringList

转载 作者:行者123 更新时间:2023-12-03 15:56:29 25 4
gpt4 key购买 nike

我正在使用 Delphi Xe5,并且我有一个组件,该组件本质上使用 IDTCPCLient(套接字)与服务器通信并以 JSON 形式检索数据。我已经为您省去了所有连接代码等。它可以工作。返回的 JSon 也可以工作。我遇到的问题是将 JSON 转换为 StringList,然后使用它将值列表写入列表框并将其余 JSON 数据对象存储在 TSTrings OBjects 属性中。

我发生了很多有趣的事情。

1.) 我一生都无法让 List 属性正常工作。我使用这个列表来存储我的 JSON。一个字符串值,然后是列表中每个项目的整个对象。您会注意到,在 JSONToStringList 方法中,我清除了字符串列表(它被注释掉,因为如果没有注释掉,我的程序就会挂起)

2.) 在为所需的多个 JSON 集多次调用该方法后,我在列表中得到重复的值

TConnector = class(TComponent)
private
{ Private declarations }
FList: TStrings;
procedure SetList(const Value: TStrings);
protected
{ Protected declarations }
public
{ Public declarations }
Constructor Create( AOwner : TComponent ); override;
Destructor Destroy; Override;
Procedure GenerateJSON;
Procedure JSONToStringList(aJSonKey: String);
published
{ Published declarations }
property List: TStrings Read FList Write SetList;

end;


Constructor TConnector.Create(AOwner: TComponent);
begin
inherited;
FList:= TStringList.Create(True);
end;


destructor TConnector.Destroy;
begin
if FList <> nil then
FreeAndNil(FList);
inherited;
end;

Procedure TConnector.GenerateJSON;
begin
if ResponseStream<>nil then
Begin
FreeAndNil(ResponseJSON_V);
ResponseJSON_V := TJSONObject.ParseJSONValue(StreamToArray(ResponseStream),0) as TJSONValue;
End;
end;

procedure TConnector.JSONToStringList(aJSonKey: String);
Var
zLJsonValue : TJSONValue;
zLJSONArray: TJSONArray;
zLJsonObject : TJSONObject;
zI : Integer;
begin
if ResponseJSON_V is TJSONArray then
begin
zLJSONArray:= ResponseJSON_V as TJSONArray;
zLJsonObject := zLJSONArray.Get(0) as TJSONObject;
end
else
if ResponseJSON_V is TJSONObject then
begin
zLJSONArray:= nil;
zLJsonObject := ResponseJSON_V as TJSONObject;
end
else
Exit;
if zLJSONArray<>nil then
begin
***//FList.Clear;***
for zLJsonValue in zLJSONArray do
begin
zLJsonObject := zLJsonValue as TJSONObject;
for zI := 0 to zLJsonObject.Size-1 do
begin
if zLJsonObject.Get(zI).JsonString.Value = aJSonKey then
begin
FList.AddObject(zLJsonObject.Get(zI).JSONValue.Value, zLJsonObject);
end;
end;
end;
end
else
begin
FList.Clear;
for zI := 0 to zLJsonObject.Size-1 do
begin
if zLJsonObject.Get(zI).JsonString.Value = aJSonKey then
FList.AddObject(zLJsonObject.Get(zI).JSONValue.Value, TJSONPair(zLJsonObject.Get(zI)));
end;
end;
end;

我希望这一切都是可以理解的。如果您需要查看更多内容,请告诉我。请随时纠正您在我的代码中发现的任何其他问题。我一直在学习:) - 谢谢你的帮助

最佳答案

  1. 如果 FList.Clear 挂起,则很可能是内存损坏问题。我怀疑的第一件事是您没有调用构造函数或者该部分内存已被其他内容覆盖。

  2. 列表中的重复值是否是由于您注释掉了 FList.Clear 而导致的。无论如何,我建议使用调试器来查看列表中的内容或记录添加到列表中/从列表中删除的所有内容。这应该能让您了解列表中不需要的值来自何处。

  3. 作为一般建议,您无需在释放对象之前检查对象是否不为 nil。无论如何,检查都是在 Free 中(或在 FreeAndNil 的 Free 部分)中进行的。

关于使用 Delphi Xe5 将 JSON 转为 StringList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19849428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com