简体   繁体   English

Java:将键值对附加到嵌套的 json 对象

[英]Java: Append key value pair to nested json object

I am given three inputs .我得到了三个输入。

  • A JSON object (nested)一个 JSON 对象(嵌套)

  • 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.我的任务是通过查看节点结构并更新原始 JSON 来将键值对附加到节点。

For example, if the inputs are,例如,如果输入是,

  1. JSON Object JSON 对象

    { a: { b: { c:{} } } }
  2. Node structure节点结构

    ab
  3. Key k and value vk和值v

The final updated JSON should look like最终更新的 JSON 应该如下所示

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

Please note that the original JSON can be {} also.请注意,原始 JSON 也可以是{} Then I have to build the whole JSON by looking at the node structure.然后我必须通过查看节点结构来构建整个 JSON。

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将其附加到 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:可以使用String#split(regex)来完成,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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