- 需求:
将以下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;
}