I was initialising a TJSONArray
as:
jsonArray := xeroResponse.JSONValue as TJSONArray;
but I had forgotten to free the TRESTResponse
. Now that I’m doing that, the jsonArray
is being freed as well.
I use the jsonArray
throughout the Form to run multiple endpoints. So I want to create it in the Form’s OnCreate
event so nothing else owns it. Then I can use it as much as I need and then free it in the Form’s OnDestroy
event.
How do I assign the xeroResponse.JSONValue
to an already created TJSONArray
?
And where I am using the TJSONArray
, I would like to create the TJSONObject
I am using, so that I can free it directly, as I won’t be freeing the jsonArray
(at that point). I was doing:
jObject := jsonArray[x] as TJSONObject;
How do I assign the jsonArray[x]
to an already created TJSONObject
?
2
Answers
You can’t.
Reading from
TRESTResponse.JSONValue
creates a newTJSONValue
-derived object when it parses the response data, and that object is freed when theTRESTResponse
is freed. You can’t change that process, and you can’t take ownership of that object.So, if you want to keep the parsed JSON object after freeing the
TRESTResponse
, you will have to make a deep copy of the object.Otherwise, don’t use
TRESTResponse.JSONValue
to begin with. UseTRESTReponse.JSONText
instead and parse it yourself, such as withTJSONObject.ParseJSONValue()
. Then you will have ownership of the object it returns.You can’t do that, either. When the JSON is parsed and creates a new
TJSONArray
, the parser will also create new objects for the array elements, too.In short, you can’t supply your own pre-created objects to the JSON parser. If that is what you want, then you need to re-think your approach.
Try
This will duplicate the object and its contents. You will then be able to free the
xeroResponse
object as well as thejsonArray
object. Note any of the objects of the array will be owned byxeroResponse
, so you can use the.Clone
function on these as well.