JSONObject遍历并替换部分json值
今天做接口对接,在更新价格时,最开始传的值为整数,发现报错,询问对方后得知需要统一保留两位小数,没有则为.00,于是对原有JSONObject进行改造,遍历并替换其中的值。下面贴出代码:
JSONObject jsonObject = JSONObject.parseObject(jsonstring);
JSONArray jsonArray = jsonObject.getJSONArray("skuList");
for (Object object : jsonArray) {
JSONObject midObject = (JSONObject) object;
BigDecimal price = midObject.getBigDecimal("price");
midObject.put("price", new BigDecimal(String.format("%.2f", price.doubleValue())));
}JSON操作讲解
- put可以强制更新json里面的值
JSONObject json = JSON.parseObject("{val: 123}");
System.out.println("======before=====");
System.out.println("size: " + json.size());
System.out.println("val: " + json.get("val"));
//直接put相同的key
json.put("val", 234);
System.out.println("======after======");
System.out.println("size: " + json.size());
System.out.println("val: " + json.get("val"));
结果
======before=====
size: 1
val: 123
======after======
size: 1
val: 234 相关推荐
somebodyoneday 2020-06-15
83163452 2020-01-28
adonislu 2020-01-10
adonislu 2019-12-31
xufankang 2019-12-19
somebodyoneday 2019-12-07
somebodyoneday 2019-10-30
ZCMUCZX 2016-04-14
WebVincent 2020-07-21
fengchao000 2020-07-04
baijinswpu 2020-06-28
88483063 2020-06-28
fengchao000 2020-06-16
wujiajax 2020-06-14
somebodyoneday 2020-05-16
xx0cw 2020-05-16
newthon 2020-05-14