java 如何编辑、修改嵌套的 JSONObject

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25894559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:54:07  来源:igfitidea点击:

How to edit, modify nested JSONObject

javajson

提问by eabyshev

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

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

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

}

}

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

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

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

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.

因此,为了在我的版本中编辑种子,在删除“种子”并放置具有新值的新“种子”后,我首先需要获取“词汇表”,然后是“GlossDiv”。

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

你能帮我找到另一种编辑方式吗?例如:只是一些方法(字符串键,字符串新值)。

采纳答案by eabyshev

I found solution.

我找到了解决方案。

    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));

回答by Sotirios Delimanolis

You don't need to removebefore calling put. JSONObject#putwill replace any existing value. Simply call

你并不需要remove调用之前putJSONObject#put将替换任何现有值。只需致电

js.getJSONObject("glossary").getJSONObject("GlossDiv").put("seeds", "555");

But how to get to wanted key for one step?

但是如何一步到位的得到想要的钥匙呢?

You don't. You have a nested object tree. You must go through the full tree to reach your element. There might be a library out there that does this for you, but underneath it all, it will be traversing everything.

你没有。您有一个嵌套的对象树。您必须遍历完整的树才能到达您的元素。可能有一个库可以为您执行此操作,但在这一切之下,它将遍历所有内容。

回答by Anzar Ansari

Update/ edit/modify nested JSON Object and converting String to JSON by using org.json.simple.JSONObject recursive call

使用 org.json.simple.JSONObject 递归调用更新/编辑/修改嵌套的 JSON 对象并将字符串转换为 JSON

JSON Input file

JSON 输入文件

{
  "Response": {
    "AccountId": "12345",
    "CompanyCode": 1,
    "CustomerName": "Joseph X. Schmoe",
    "EmailAddressList": {
      "Response.EmailAddressDTO": {
        "AlertOptionList": null,
        "ContactMethodSeqNum": 2,
        "EmailAddress": null
      }
    },
    "MailingAddress": {
      "NonStandard": null,
      "Standard": {
        "Address": "Example",
        "DisplayAddressText": null
      }
    },
    "LastBill": null,
    "LastPayment": null
  }
}

Code for the converting String to JSON Object and Updating the Nested JSON object value against the specific Key Example: "Address": "Addressxxxxxx",

用于将字符串转换为 JSON 对象并根据特定关键示例更新嵌套 JSON 对象值的代码:“地址”:“Addressxxxxxx”,

public static void main(String[] args) throws IOException {

        FileInputStream inFile = new FileInputStream("File_Location");
        byte[] str = new byte[inFile.available()];
        inFile.read(str);
        String string = new String(str);
        JSONObject json = JSONEdit.createJSONObject(string);
        System.out.println(JSONEdit.replacekeyInJSONObject(json,"Address","Addressxxxxxx"));
    }

    private static JSONObject replacekeyInJSONObject(JSONObject jsonObject, String jsonKey,
            String jsonValue) {

        for (Object key : jsonObject.keySet()) {
            if (key.equals(jsonKey) && ((jsonObject.get(key) instanceof String)||(jsonObject.get(key) instanceof Number)||jsonObject.get(key) ==null)) {
                jsonObject.put(key, jsonValue);
                return jsonObject;
            } else if (jsonObject.get(key) instanceof JSONObject) {
                JSONObject modifiedJsonobject = (JSONObject) jsonObject.get(key);
                if (modifiedJsonobject != null) {
                    replacekeyInJSONObject(modifiedJsonobject, jsonKey, jsonValue);
                }
            }

        }
        return jsonObject;
    }

    private static JSONObject createJSONObject(String jsonString){
        JSONObject  jsonObject=new JSONObject();
        JSONParser jsonParser=new  JSONParser();
        if ((jsonString != null) && !(jsonString.isEmpty())) {
            try {
                jsonObject=(JSONObject) jsonParser.parse(jsonString);
            } catch (org.json.simple.parser.ParseException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

JSON Output:

JSON 输出:

{
  "Response": {
    "AccountId": "12345",
    "CompanyCode": 1,
    "CustomerName": "Joseph X. Schmoe",
    "EmailAddressList": {
      "Response.EmailAddressDTO": {
        "AlertOptionList": null,
        "ContactMethodSeqNum": 2,
        "EmailAddress": null
      }
    },
    "MailingAddress": {
      "NonStandard": null,
      "Standard": {
        "Address": "Addressxxxxxx",
        "DisplayAddressText": null
      }
    },
    "LastBill": null,
    "LastPayment": null
  }
}