When i try to unmarshall a JSON object that is not well formated, I expect a object reference from UnMarshall function, but it comes nil. But so, when I close my application that object generates memory leaks.
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;
If the JSON object was not in expected format, it raises an exception but don't destroy object created reference and don't return it on function.
So someone that consumes my server can call some functions and nothing garanties the JSON sended into request is well formatted.
How can I handle this kind of situation? There's a way to validate the JSON object with the respective class?
ps: I'm using Delphi XE7