Appearance
Objects References And Deep Copying
Whenever you access any TJSONValue descendants, you are actually dealing with references to them. It means that the following operation will not end up with a new instance of JSON object:
pascal
var
Obj1, Obj2: TJSONObject;
begin
…
Obj2 := Obj1[‘subobject’] as TJSONObject;
Obj1.Free;
end;In the example, Obj2 is referencing to a subobject of Obj1. That is why we should not release memory of Obj2 since it is also a part of Obj1.
However, we might need to obtain a deep copy of a TJSONObject or TJSONArray. In this case, method Clone can be used:
pascal
var
Obj1, Obj2: TJSONObject;
begin
…
Obj2 := Obj1[‘subobject’].Clone as TJSONObject;
Obj1.Free;
Obj2.Free;
end;Here we have to release memory of both objects, because Obj2 is not included in Obj1 anymore. Obj2 is a deep copy of a subobject of Obj1 with exactly the same data, but its own allocated memory.

