jsonobject修改key的值_JSONObject(org.json)的一点修改 | 学步园

本文介绍了一个对org.json.JSONObject的修改,优化了stringToValue方法,使其在处理可能的数值字符串时,返回能容纳整数的最小包装类型,避免在数据交互中出现异常。同时增加了对byte和short类型的put方法,方便直接存入JSONObject。
摘要由CSDN通过智能技术生成

修改org.json.JSONObject的stringToValue,返回能容纳整数的最小包装类型而不是Integer。

(修正数据交互工具中当对象包含属性的类型为类型为byte/short时反射调用field.set(bean, obj)引发异常。)

黑色粗体斜体为增加部分,修改后代码如下:

static public Object stringToValue(String s) {

if (s.equals("")) {

return s;

}

if (s.equalsIgnoreCase("true")) {

return Boolean.TRUE;

}

if (s.equalsIgnoreCase("false")) {

return Boolean.FALSE;

}

if (s.equalsIgnoreCase("null")) {

return JSONObject.NULL;

}

/*

* If it might be a number, try converting it.

* We support the non-standard 0x- convention.

* If a number cannot be produced, then the value will just

* be a string. Note that the 0x-, plus, and implied string

* conventions are non-standard. A JSON parser may accept

* non-JSON forms as long as it accepts all correct JSON forms.

*/

char b = s.charAt(0);

if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {

if (b == '0' && s.length() > 2 &&

(s.charAt(1) == 'x' || s.charAt(1) == 'X')) {

try {

return new Integer(Integer.parseInt(s.substring(2), 16));

} catch (Exception ignore) {

}

}

try {

if (s.indexOf('.') > -1 ||

s.indexOf('e') > -1 || s.indexOf('E') > -1) {

return Double.valueOf(s);

} else {

Long myLong = new Long(s);

if (myLong.shortValue() == myLong.byteValue()) {

return new Byte(myLong.byteValue());

} if (myLong.intValue() == myLong.shortValue()) {

return new Short(myLong.shortValue());

}

if (myLong.longValue() == myLong.intValue()) {

return new Integer(myLong.intValue());

} else {

return myLong;

}

}

}  catch (Exception ignore) {

}

}

return s;

}

还有org.json.JSONObject中增加:

/**

* Put a key/int pair in the JSONObject.

*

* @param key   A key string.

* @param value An int which is the value.

* @return this.

* @throws JSONException If the key is null.

*/

public JSONObject put(String key, byte value) throws JSONException {

put(key, new Byte(value));

return this;

}

/**

* Put a key/int pair in the JSONObject.

*

* @param key   A key string.

* @param value An int which is the value.

* @return this.

* @throws JSONException If the key is null.

*/

public JSONObject put(String key, short value) throws JSONException {

put(key, new Short(value));

return this;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值