简体   繁体   中英

Java: Append key value pair to nested json object

I am given three inputs .

  • A JSON object (nested)

  • A node structure

  • key value pair

My task is to append the key value pair to a node by looking at the node structure and updating the original JSON.

For example, if the inputs are,

  1. JSON Object

    { a: { b: { c:{} } } }
  2. Node structure

    ab
  3. Key k and value v

The final updated JSON should look like

    {
      a:
         {
           b:
              {
                key:val
                c:{}
              }     
         }
    }

Please note that the original JSON can be {} also. Then I have to build the whole JSON by looking at the node structure.

Here is my code

  • making a key value pair

     public JSONObject makeEV(String ele, String val) throws JSONException{ JSONObject json =new JSONObject(); json.put(ele, val); return json; }
  • Appending it to JSON

     public void modifiedJSON(JSONObject orgJson, String nodeStruct, JSONObject ev) throws JSONException{ JSONObject newJson = new JSONObject(); JSONObject copyJson = newJson; char last = nodeStruct.charAt(nodeStruct.length()-1); String lastNode = String.valueOf(last); int i = 0; while(orgJson.length() != 0 || i< nodeStruct.length()){ if(orgJson.length() ==0){ if(nodeStruct.charAt(i) == last){ newJson.put(String.valueOf(last), ev.toString()); }else{ newJson.put(String.valueOf(nodeStruct.charAt(i)), ""); } newJson = newJson.getJSONObject(String.valueOf(nodeStruct.charAt(i))); } else if(i >= nodeStruct.length()){ if(orgJson.has(lastNode)){ newJson.put(String.valueOf(last), ev.toString()); }else{ } } } }

    I am stuck here. Please help. Thanks in advance.

It could be done using String#split(regex) as next:

public void modifiedJSON(JSONObject orgJson, String nodeStruct, 
                         String targetKey, String value)  {
    // Split the keys using . as separator 
    String[] keys = nodeStruct.split("\\.");
    // Used to navigate in the tree
    // Initialized to the root object
    JSONObject target = orgJson;
    // Iterate over the list of keys from the first to the key before the last one
    for (int i = 0; i < keys.length - 1; i++) {
        String key = keys[i];
        if (!target.has(key)) {
            // The key doesn't exist yet so we create and add it automatically  
            target.put(key, new JSONObject());
        }
        // Get the JSONObject corresponding to the current key and use it
        // as new target object
        target = target.getJSONObject(key);
    }
    // Set the last key
    target.put(targetKey, value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM