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

时间:2016-10-06 11:53:56

标签: java json

我有三个输入。

  • JSON对象(嵌套)

  • 节点结构

  • 键值对

我的任务是通过查看节点结构并更新原始JSON来将键值对附加到节点。

  

例如,如果输入是

  1. JSON对象

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

    a.b.
    
  3. k和值v

  4. 最终更新的JSON应该看起来像

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

    请注意,原始JSON也可以是{}。然后我必须通过查看节点结构来构建整个JSON。

    这是我的代码

    • 制作一个键值对

       public JSONObject makeEV(String ele, String val) throws JSONException{      
         JSONObject json =new JSONObject();
         json.put(ele, val);
         return 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{
      
              }
          }
      }
      }
      

      我被困在这里。请帮忙。提前致谢。

1 个答案:

答案 0 :(得分:1)

可以使用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);
}
相关问题