2016-10-06 219 views
1

我給出了三個輸入。Java:將鍵值對追加到嵌套的json對象

  • JSON對象(嵌套)

  • 的節點結構

  • 鍵值對

我的任務是通過觀察到追加關鍵值對的節點節點結構並更新原始的JSON。

例如,如果輸入是,

  1. JSON對象

    { 
        a: 
        { 
         b: 
          { 
          c:{} 
          }  
        } 
    } 
    
  2. 節點結構

    a.b. 
    
  3. 密鑰k和價值v

最後更新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{ 
    
         } 
        } 
    } 
    } 
    

    我在這裏停留。請幫忙。提前致謝。

+0

你的節點結構應該是相當'a.b.key',不是嗎? –

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

實際上,這裏ev是我需要插入的關鍵值對。 –

+0

您可以進行必要的更改嗎? –

+0

謝謝。如果密鑰是作爲單獨的參數給出的,並且節點結構是'a.b.'會怎麼樣? –