Android移动开发之【Android实战项目】DAY14-修改json里某个字段的值

注释:
直接调用就可以.  第一个参数为key,第二个为值,第三个传一个整串json的jsonObject.


/**
     * 解析Json数据.
     *
     * @param key    更换数据key
     * @param value  更换Value
     * @param object 解析对象
     */
    public void analyzeJson(String key, Object value, Object object) {
        try {
            if (object instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) object;
            for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            analyzeJson(key, value, jsonObject);
            }
             } else if (object instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) object;
                Iterator iterator = jsonObject.keys();
                while (iterator.hasNext()) {
                    String jsonKey = iterator.next().toString();
                    Object ob = jsonObject.get(jsonKey);
                    if (ob != null) {
                        if (ob instanceof JSONArray) {
                            analyzeJson(key, value, ob);
                        } else if (ob instanceof JSONObject) {
                            analyzeJson(key, value, ob);
                        } else {
                            if (jsonKey.equals(key)) {
                                jsonObject.put(key, value);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

发布了610 篇原创文章 · 获赞 140 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43838785/article/details/104370751