12

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

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

}

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

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.

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

eabyshev
  • 703
  • 2
  • 8
  • 16

4 Answers4

9

You don't need to remove before calling put. JSONObject#put will replace any existing value. Simply call

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

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));
eabyshev
  • 703
  • 2
  • 8
  • 16
1

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

JSON Input file

{
  "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",

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:

{
  "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
  }
}
Anzar Ansari
  • 109
  • 1
  • 5
  • It's difficult to make use of a picture of code, and much more helpful if your answer contains the code itself as text – camille Dec 03 '19 at 17:46
  • Thank you very much for your response. The code has been updated in-text format. – Anzar Ansari Dec 04 '19 at 10:09
  • This code works fine but when you convert JSONObject back to json string using toString() or toJsonString(), the order of element will be changed and it's different from original json string. – vermap Feb 25 '20 at 22:11
  • @vermap I agree with you, unfortunate this issue I also faced, because JSON contains a Key-Value pair so we need to use Map for this and we know that Map will store the value in unorder fashion, we can overcome this by the following ways 1. overriding the constructor instead of using the default Map of Json we can take LinkedHashMap by overriding the constructor. 2. Simple File operation and change the value. 3. Use some third party API such as Jackson – Anzar Ansari Mar 03 '20 at 15:30
  • @anzaransari Yeah true that, I am currently using option 2 (replace string values), I know its not efficient way but that's only working option I found. Jackson was on the other hand a good option if your json has limited number of tag (in my case there are thousand of tag and some of the online tools were even unable to create mapper classes from given json). Gonna give a try to option 1. Thanks for sharing it. – vermap Mar 04 '20 at 16:06
0

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