Arun Arun - 1 year ago 112
JSON Question

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

How do you set the value for a key to an integer using JSONObject in Java?
I can set String values using


However, I am not able to figure out how to use
to set integer values. For example:
I want my jsonobject to look like this:
{"age": 35}

instead of
{"age": "35"}

Answer Source

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!


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download