JSON
来源:互联网 发布:网络工程项目 编辑:程序博客网 时间:2024/05/21 13:56
- 需求:
将以下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;}
阅读全文
0 0
- Json
- JSON
- JSON
- JSON
- json
- JSON
- JSON
- json
- Json
- json
- JSON
- json
- json
- JSON
- json
- JSON
- JSON
- json
- Deep Learning读书笔记4---深度模型中的优化
- win10修改jdk版本不生效
- springMvc简要总结
- docker入门之安装
- 4、Spring Session-HttpSession整合工作原理
- JSON
- iOS之《Effective Objective-C 2.0》读书笔记(51)
- 自适应网页设计(Responsive Web Design)
- docker入门之镜像
- 移植Openssh到ARM Linux目标板
- datatable linq查询
- java_获取“当前时间”的方法
- intellij 控制台输出乱码
- Python 中的argsort()函数的用法