【发布时间】:2013-11-08 00:20:58
【问题描述】:
我正在使用 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;
我希望这一切都可以理解。如果您需要查看更多信息,请告诉我。请随时纠正您在我的代码中看到的任何错误。我一直在学习:) - 谢谢你的帮助
【问题讨论】:
-
显示 JSON 文件本身。另请参阅“如何从数组中读取值?” superobject.googlecode.com/git/readme.html中的部分
标签: json delphi delphi-xe5