當我嘗試解組不合時宜的JSON對象時,我期望從UnMarshall函數獲得對象引用,但它會出現nil。但是,當我關閉我的應用程序時,該對象會產生內存泄漏。如何安全UnMarshal JSON對象
TMyObject = class
private
FName: String;
end;
AJSON := TJSONObject.ParseJSONValue('{ type: "MyObject.TMyObject", id: 1, fields: { FName: "David", FAge: 20 } }');
//FAge attribute don't exists in TMyObject, so it raises an exception when unmarshalling
with TJSONUnMarshal.Create() do
begin
try
Result := Unmarshal(AJSON);
//First chance exception at $77322F71. Exception class EConversionError with message 'Internal: Field FAge cannot be found in type TMyObject'. Process MyApp.exe (3056)
finally
Free();
end;
//Here the result is nil, but internally the object was created and is alive
end
function TJSONUnMarshal.Unmarshal(Data: TJSONValue): TObject;
var
Root: TJSONObject;
begin
if not (Data is TJSONObject) then
raise EConversionError.Create(SCannotCreateObject);
// clear previous warnings
ClearWarnings;
Root := TJSONObject(Data);
try
Result := CreateObject(Root)
finally
FObjectHash.Clear;
end;
end;
如果JSON對象不是預期的格式,它拋出一個異常,但不破壞對象創建參考,並不會返回它的功能。
因此,使用我的服務器的用戶可以調用某些函數並且不需要任何服務,JSON發送到請求的格式很好。
我該如何處理這種情況?有一種方法可以驗證各個類的JSON對象嗎?
PS:我用Delphi XE7
哪個對象沒有被銷燬。問題中的代碼似乎沒有問題。 – 2014-09-30 16:56:35
在Unmarshal中創建的對象。該函數創建該對象並引發異常,但不會執行任何結果,它將返回零並且該對象處於活動狀態。 – Lucas 2014-09-30 17:00:15
傳遞nil作爲參數在函數中得到了很好的處理,它通過「assert(JsonObj <> nil)」在「CreateObject(JsonObj:TJSONObject)」中進行檢查; – Lucas 2014-09-30 17:06:39