JSON - 更新json中特定类型的数据

  • 需求:
    将以下json字符串中的 "needPower":0.0 的值 0.0 调整为 0 ,也即值类型由double 调整为 int
//输入
{"entityId":"0ccd079d-ec1f-404e-a9d5-cfbe965aca6b","recId":"26e6dc92-dab8-4a0c-a26f-1606e78038b0","needPower":0.0}
//输出
{"entityId":"0ccd079d-ec1f-404e-a9d5-cfbe965aca6b","recId":"26e6dc92-dab8-4a0c-a26f-1606e78038b0","needPower":0}
  • 分析
    前面例子中的 json字符串只是简单的一个JSONObject,但实际使用时可能是包含各种类型的json,如包含JSONObject 、JSONArray、Double、Int 等等
    对需求的调整json中所有的 Double 类型 xx.0 (不包括xx.y ,y不等于0)为xx Int 类型来说,有影响的数据类型有 JSONObject 、JSONArray、Double。所以在处理中要考虑这三种类型才全面。

  • 代码处理

String jsonString = "{"entityId":"0ccd079d-ec1f-404e-a9d5-cfbe965aca6b","recId":"26e6dc92-dab8-4a0c-a26f-1606e78038b0","needPower":0.0}";  

jsonString  = argsAdjust(jsonString ); //进行json调整  
private String argsAdjust(String args) {
    try {
        JSONObject jsonObject = new JSONObject(args);
        jsonObject = (JSONObject) jsonAdjust(jsonObject);
        return jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return args;
}
/**
 * 对输入的对象进行调整
 */
private Object jsonAdjust(Object input){
    if (input instanceof JSONObject){//JSONObject 类型

        JSONObject jsonObject = (JSONObject) input;
        Iterator<String> iterator = jsonObject.keys();
        while (iterator.hasNext()){
            String key = iterator.next();
            try {
                Object object = jsonObject.get(key);
                object = jsonAdjust(object);//递归处理
                jsonObject.put(key,object);//更新值
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return jsonObject;

    }

    if (input instanceof JSONArray){//JSONArray 类型
        JSONArray jsonArray = (JSONArray) input;

        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                Object object = jsonArray.get(i);
                object = jsonAdjust(object);
                jsonArray.put(i,object);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsonArray;
    }

    if (input instanceof Double){//Double 类型
        int result = 0;
        double d = (Double) input;
        if(new BigDecimal(d).compareTo(new BigDecimal((int)d)) == 0){//d小数点后为0
            result = (int) d;
            return result;
        }
    }

    return input;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值