如何编辑,修改嵌套的JSONObject [英] How to edit, modify nested JSONObject

查看:139
本文介绍了如何编辑,修改嵌套的JSONObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能帮我解决这个问题吗? 例如我有JSONEObject

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

{
"glossary": {
    "title": "example glossary",
    "GlossDiv": {
        "title": "S",
        "seeds": "12415",
    }
}

}

例如,我需要将种子":"12415"更改为种子":"555". 我找到了一些解决方案:

For example, I need change "seeds":"12415" to "seeds":"555". I found some solution:

JSONObject js = new JSONObject(jsonString);
js.getJSONObject("glossary").getJSONObject("GlossDiv").remove("seeds");
js.getJSONObject("glossary").getJSONObject("GlossDiv").put("seeds","555");

因此,要在我的版本中编辑种子,我需要先获取词汇表",然后获取"GlossDiv",然后再删除种子"并放入具有新值的新种子".

So for editing seeds in my version I need first to get "glossary" then "GlossDiv" after I delete "seeds" and put new "seeds" with new value.

您能帮我找到另一种编辑方式吗?例如:只是somemethod(String key,String NewValue).

Could you help me to find another way to edit? For example: just somemethod(String key,String NewValue).

推荐答案

我找到了解决方法.

    public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
    String[] keyMain = keys.split("\\.");
    for (String keym : keyMain) {
        Iterator iterator = js1.keys();
        String key = null;
        while (iterator.hasNext()) {
            key = (String) iterator.next();
            if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
                if ((key.equals(keym))) {
                    js1.put(key, valueNew);
                    return js1;
                }
            }
            if (js1.optJSONObject(key) != null) {
                if ((key.equals(keym))) {
                    js1 = js1.getJSONObject(key);
                    break;
                }
            }
            if (js1.optJSONArray(key) != null) {
                JSONArray jArray = js1.getJSONArray(key);
                for (int i = 0; i < jArray.length(); i++) {
                    js1 = jArray.getJSONObject(i);
                }
                break;
            }
        }
    }
    return js1;
}

public static void main(String[] args) throws IOException, JSONException {
    FileInputStream inFile = new FileInputStream("/home/ermek/Internship/labs/java/task/test5.json");
    byte[] str = new byte[inFile.available()];
    inFile.read(str);
    String text = new String(str);
    JSONObject json = new JSONObject(text);
    setProperty(json, "rpc_server_type", "555");
    System.out.println(json.toString(4));

这篇关于如何编辑,修改嵌套的JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆