Caution while Pushing JSONObject to a JSONArray

Fakrudeen Ali T
1 min readApr 13, 2020

--

Let me start with the question directly. Can u guess what will be stored in result array ?

Question

If your guess is result = [{“name”:”Alice”,”age”:”20"},{“name”:”Bob”,”age”:”30"}]. Welcome to the club. It is wrong !! The result here will be [{“name”:”Bob”,”age”:”30"},{“name”:”Bob”,”age”:”30"}].

If you are wondering why, the JSONArray always stores reference of the JSONObject which is pushed into it. Hence, even-though the JSONObject is overwritten after pushing into the array, the overwritten object’s value will be reflected in the array too.

What is the fix then ? Simply, Clearing the reference of the JSONObject before overwriting should do the magic !

Fix

It will give the expected result = [{“name”:”Alice”,”age”:”20"},{“name”:”Bob”,”age”:”30"}].

HAPPY CODING !

--

--

No responses yet