Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit, modify nested JSONObject

Tags:

java

json

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

like image 721
eabyshev Avatar asked Sep 17 '14 15:09

eabyshev


People also ask

How to modify JSON data in SQL Server?

This article explores JSON_MODIFY () function to modify JSON Data in the SQL Server. Java Script Object Notation is a popular language in major NoSQL databases and applications for mobile development. SQL Server 2016 introduced native support for JSON. Suppose you define a variable in SQL Server and it holds JSON key-value pairs.

How to add another JSON string to an existing JSON string?

For example, a JSON string can contain another JSON string in its property. For example, suppose we want to add a JSON object that contains seller information in the existing JSON. We need to specify the new JSON in the third parameter. For simplicity purposes, it’s better to declare a variable and contain JSON into it similar to the below code.

How to dynamically modify the values of a JSON object?

Considering JS over here, you can dynamically modify the values of a JSON object in many ways. Let’s take the following example :- The whole nested object is assigned to the variable result. Now suppose, we h myObj.cars.car3 = “suzuki” //accessing object and changing value you will find cars.car3 value is now suzuki instead of “Flait”

How to update the JSON string using JSON_modify?

We use JSON_MODIFY () function to update the JSON string. It can update the following items: Update existing property value Add a new element in an existing array


3 Answers

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.

like image 111
Sotirios Delimanolis Avatar answered Nov 05 '22 14:11

Sotirios Delimanolis


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));
like image 35
eabyshev Avatar answered Nov 05 '22 14:11

eabyshev


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
  }
}
like image 37
Anzar Ansari Avatar answered Nov 05 '22 15:11

Anzar Ansari