Athul Sukumaran Athul Sukumaran - 2 months ago 18
JSON Question

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

    a.b.

  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.


Answer

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