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 !!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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:
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 theputmethod is an Object and the first parameter to theelementmethod is aString. Theputmethod simply does aString.valueOf()on the first parameter sent into it and then calls theelementmethod, so basically they both do the same thing, onlyputis more flexible and technically allows non-string keys that are then converted into strings before calling theelementmethod.In a nutshell, they have different parameters and return values, but the
putmethod 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
elementdue to the similarities to that language in that the method returns the calling object.