【发布时间】:2013-07-03 08:24:17
【问题描述】:
尝试使用 TJSONObject (Delphi XE4) 解析 JSON 文件。
解析后我想销毁 TJSONObject 以防止内存泄漏,但是:
procedure TfmMain.ReadIngrJSON(const fName: string);
var i: integer;
S: TStringList;
JSONObject, innerObject: TJSONObject;
innerArray: TJSONArray;
begin
S:=TStringList.Create;
try
S.LoadFromFile(fName);
JSONObject:=TJSONObject.ParseJSONValue(S.Text) as TJSONObject;
if Assigned(JSONObject) then
begin
SetLength(ingrArray, JSONObject.Size);
for i := 0 to JSONObject.Size-1 do
begin
ingrArray[i].id:=JSONObject.Get(i).JsonString.Value;
innerObject:=JSONObject.Get(ingrArray[i].id).JsonValue as TJSONObject;
innerArray:=innerObject.Get('en').JsonValue as TJSONArray;
ingrArray[i].name[0]:=innerArray.Get(0).Value;
ingrArray[i].units[0]:=innerArray.Get(1).Value;
innerArray:=innerObject.Get('ru').JsonValue as TJSONArray;
ingrArray[i].name[1]:=innerArray.Get(0).Value;
ingrArray[i].units[1]:=innerArray.Get(1).Value;
innerArray:=nil;
end;
innerObject.Destroy;
for i := 0 to Length(ingrArray)-1 do
listIngredients.Items.Add(ingrArray[i].name[1]);
end
else
raise Exception.Create('no JSON data');
finally
JSONObject.Destroy; //here is an error 'invalid pointer operation'
S.Free;
end;
end;
我的代码有什么问题?
【问题讨论】:
-
为什么不使用
SuperObject?它使用引用计数,因此您可以忘记创建和释放。它还经过多年广泛使用的测试,并且多次报告 DBx JSOn 存在错误或效率低下。 superobject.googlecode.com/git/readme.html -
BTW
try应该在对象创建之后,而不是之前。不知道您现在是否面临该特定错误,但您的客户在尝试Destroy垃圾指针时可能会受到打击。 -
我最好闭嘴但是:你为什么不使用
.Free()?当您强行尝试销毁已被销毁的对象时,通常会抛出“无效指针操作”。Free()首先检查对象是否已分配,然后尝试销毁它。但你可能有这样做的理由,我对 Delphi 中的 JSON 真的一无所知...... -
@GünthertheBeautiful
.Free如果对象变量被预置零(IOW 它是另一个对象的属性)或在您使用FreeAndnil(许多 Delphi 专家认为有害)之后可能会对您有所帮助。在这个特定的代码中,它可能隐藏在问题上(无指针情况),真的。但它不会也不能用垃圾指针的情况提供任何保护。 PS。.Free是为对象析构函数引入的,利用了提到的属性自动归零功能。它将在一般代码中使用而不是析构函数只是与计划路径的意外偏差:-) -
@Arioch'The:我已经使用过超级对象。现在我想使用 DBXJSON ))
标签: json delphi delphi-xe4