skip to Main Content

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


  1. How do I assign the xeroResponse.JSONValue to an already created TJSONArray?

    You can’t.

    Reading from TRESTResponse.JSONValue creates a new TJSONValue-derived object when it parses the response data, and that object is freed when the TRESTResponse 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. Use TRESTReponse.JSONText instead and parse it yourself, such as with TJSONObject.ParseJSONValue(). Then you will have ownership of the object it returns.

    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?

    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.

    Login or Signup to reply.
  2. Try

    jsonArray := (xeroResponse.JSONValue as TJSONArray).Clone;
    

    This will duplicate the object and its contents. You will then be able to free the xeroResponse object as well as the jsonArray object. Note any of the objects of the array will be owned by xeroResponse, so you can use the .Clone function on these as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search