如何在Java中使用JSONObject将键的值设置为整数?
我可以使用JSONObject.put(a,b);
设置字符串值
但是,我无法弄清楚如何使用.put()
来设置整数值。例如:
我希望我的jsonobject看起来像这样:
{"age": 35}
代替
{"age": "35"}
。
答案 0 :(得分:3)
您可以使用put将整数作为int存储在对象中,当您实际提取和解码需要进行某些转换的数据时更是如此。
所以我们创建了JSONObject
JSONObject jsonObj = new JSONObject();
然后我们可以添加我们的int!
jsonObj.put("age",10);
现在要将它作为整数返回,我们只需要在解码时将其转换为int。
int age = (int) jsonObj.get("age");
JSONObject存储它的方式并不多,但更多的是如何检索它。
答案 1 :(得分:-1)
如果你正在使用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");
请记住,您有其他“获取”方法,例如:
myJsonObject.getDouble("key");
myJsonObject.getLong("key");
myJsonObject.getBigDecimal("key");