How to edit, modify nested JSONObject

前端 未结 4 1648
野趣味
野趣味 2021-02-14 21:29

Could you help me with this issue please. for example I have JSONEObject

{
\"glossary\": {
    \"title\": \"example glossary\",
    \"GlossDiv\": {
        \"ti         


        
4条回答
  •  既然无缘
    2021-02-14 22:20

    Here i have written a simple function with recursion:

    public static JSONObject replaceAll(JSONObject json, String key, String newValue) throws JSONException {
        Iterator keys = json.keys();
        while (keys.hasNext()) {
            String k = (String) keys.next();
            if (key.equals(k)) {
                json.put(key, newValue);
            }
            Object value = json.opt(k);
            if (value != null && value instanceof JSONObject) {
                replaceAll((JSONObject) value, key, newValue);
            }
        }
        return json;
    }
    

提交回复
热议问题