Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set an integer value with JSONObject in Java?

Tags:

java

json

integer

How do you set the value for a key to an integer using JSONObject in Java? I can set String values using JSONObject.put(a,b); However, I am not able to figure out how to use .put() to set integer values. For example: I want my jsonobject to look like this: {"age": 35} instead of {"age": "35"}.

like image 313
Arun Avatar asked Sep 20 '26 08:09

Arun


2 Answers

You can store the integer as an int in the object using put, it is more so when you actually pull and decode the data that you would need to do some conversion.

So we create our JSONObject

JSONObject jsonObj = new JSONObject();

Then we can add our int!

jsonObj.put("age",10);

Now to get it back as an integer we simply need to cast it as an int on decode.

int age = (int) jsonObj.get("age");

It isn't so much how the JSONObject is storing it but more so how you retrieve it.

like image 106
basic Avatar answered Sep 21 '26 22:09

basic


If you're using org.json library, you just have to do this:

JSONObject myJsonObject = new JSONObject();
myJsonObject.put("myKey", 1);
myJsonObject.put("myOtherKey", new Integer(2));
myJsonObject.put("myAutoCastKey", new Integer(3));

int myValue = myJsonObject.getInt("myKey");
Integer myOtherValue = myJsonObject.get("myOtherKey");
int myAutoCastValue = myJsonObject.get("myAutoCastKey");

Remember that you have others "get" methods, like:

myJsonObject.getDouble("key");
myJsonObject.getLong("key");
myJsonObject.getBigDecimal("key");
like image 43
shimatai Avatar answered Sep 21 '26 21:09

shimatai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!