Search code examples
javajsonjson-lib

Difference between .put() and .element() methods in JSON?


I am trying to create json object for my data.

i found that, i can do that using two methods :-

put() and element()

please suggest me, which should be used.

my data is for example :-

key="id" value=32

Thanks in advance !!


Solution

  • After inspecting the source code it seems that the differences betwee put and element are very minimal.

    The main difference is that put appears to return the object that was previously at the key you entered's position in the properties map. So if you had a JSONObject structured like so:

    {
        "steve": 4,
        "betty": 5
    }
    

    and executed a command like this:

    Object frank = myJsonObject.put("steve", 10);

    The value of frank would now be 4 and the json object would now look like this:

    {
        "steve":10,
        "betty":5
    }
    

    If you had used .element("steve", 10); in the same situation, the object returned from the method is actually your JSONObject instead. The other difference between the two is that the first parameter to the put method is an Object and the first parameter to the element method is a String. The put method simply does a String.valueOf() on the first parameter sent into it and then calls the element method, so basically they both do the same thing, only put is more flexible and technically allows non-string keys that are then converted into strings before calling the element method.

    In a nutshell, they have different parameters and return values, but the put method just calls the element method anyway, so there is not really a difference within the JSONObject, but possibly in your external code.

    I'm guessing jQuery users would prefer to use element due to the similarities to that language in that the method returns the calling object.