java替换JSONObject某个KEY的VALUE值

Java 11-09 17:54

java 替换JSONObject某个KEY的VALUE值

在最近的工作中,需要把JSONArray里面的 jsonObject 的某一个KEY的Value值替换,需要跟新的key值来进行对比,列办法,用轮询来判断替换。

需求:把[{"userId":"12","devCallUrl":"http://www.baidu.com":"devSecret":"SHUEJDUE"},{"userId":"13","devCallUrl":"http://www.sina.com":"devSecret":"NDJDUEFID"}]中userid=12的devCallUrl的值替换为"http://www.so.com"。

用笨一点的办法来轮询处理,原理是读取之前的,然后根据key来判断,写入到新的JSONArray里面


Long userID = 12;
String pushUrl = "http://www.so.com";
boolean isDevInfoAdd = true;
JSONArray devInfoList = JSONArray.parseArray("[{"userId":"12","devCallUrl":"http://www.baidu.com":"devSecret":"SHUEJDUE"},{"userId":"13","devCallUrl":"http://www.sina.com":"devSecret":"NDJDUEFID"}]");
JSONArray newDevInfo = new JSONArray();
for(int j=0,jLen=devInfoList.size(); j<jLen; j++) {
  JSONObject jsonObject = devInfoList.getJSONObject(j);
  String devUserId = jsonObject.getString("userId");
  if(String.valueOf(userID).equals(devUserId)) { //修改
    if(pushUrl != null) {
      JSONObject newObject = new JSONObject();
           newObject.put("userId", devUserId);
           newObject.put("devCallUrl", pushUrl);
           newObject.put("devSecret", apiKey);
           newDevInfo.add(newObject);
    }
    isDevInfoAdd = false;
  } else {
    newDevInfo.add(jsonObject);
  }
}
// 新增
if(isDevInfoAdd && pushUrl != null) {
  JSONObject newObject = new JSONObject();
  newObject.put("userId", String.valueOf(userID));
  newObject.put("devCallUrl", pushUrl);
  newObject.put("devSecret", apiKey);
  newDevInfo.add(newObject);
}

相关推荐