如何在 Java 中使用 JSONObject 设置整数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37999822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:01:23  来源:igfitidea点击:

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

javajsonintegerputjsonobject

提问by Arun

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"}.

如何在 Java 中使用 JSONObject 将键的值设置为整数?我可以使用设置字符串值JSONObject.put(a,b);但是,我无法弄清楚如何使用.put()设置整数值。例如:我希望我的 jsonobject 看起来像这样: {"age": 35}而不是 {"age": "35"}.

回答by basic

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.

您可以使用 put 将整数作为 int 存储在对象中,当您实际提取和解码需要进行一些转换的数据时更是如此。

So we create our JSONObject

所以我们创建我们的 JSONObject

JSONObject jsonObj = new JSONObject();

Then we can add our int!

然后我们可以添加我们的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 即可。

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

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

与 JSONObject 存储它的方式无关,更重要的是您如何检索它。

回答by shimatai

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

如果您使用 org.json 库,则只需执行以下操作:

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");