2012-12-06 265 views
1

我想我已經做了這樣的如何動態添加到Java中的JSON對象中的嵌套元素?

JSONObject jsonObject = new JSONObject(); 
jsonObject.put("nodes", "var postLoadData = {\n nodes:{408868239:{'tipo':'clase','shape':'dot','label':'clase2'},843594076:{'tipo':'clase','shape':'dot','label':'ESTADIA'}}," + 
       "edges:{\n 2:{408868239:{},843594076:{}}}};\n \n sys.graft(postLoadData);"); 

我需要動態地添加邊和結這個JSON對象JSON對象,相當於

var data = {"nodes":"var postLoadData = {\n nodes:{408868239:{'tipo':'clase','shape':'dot','label':'clase2'},843594076:{'tipo':'clase','shape':'dot','label':'ESTADIA'}},edges:{\n 2:{408868239:{},843594076:{}}}};\n \n sys.graft(postLoadData);"} 

。怎麼做。

+0

是否要修改Java或Javascript中的JSON? –

+0

在java中我想修改。 –

+0

數據對象將在語法上有效的JSON,並不真正適用於動態添加任何東西。你可能想考慮重構你的格式。 – Perception

回答

0

您是否閱讀過API的JSONObject它定義了您將需要的操作。從我可以看到你將需要操縱鍵值nodes

我很好奇,看看你的JS會看起來像給你有你的JSON中的JS。您打算撥打exec嗎?我會非常小心如何實施。 JSON用於交換數據,你試圖做的是交換JS,這不是它的目的,也不安全。

+0

在Java腳本側調用只是eval(data.nodes) –

0

你不必JSON,你必須在該字符串這是什麼javascript代碼:

var postLoadData = { 
    nodes: { 
     408868239: { 
      'tipo': 'clase', 
      'shape': 'dot', 
      'label': 'clase2' 
     }, 
     843594076: { 
      'tipo': 'clase', 
      'shape': 'dot', 
      'label': 'ESTADIA' 
     } 
    }, 
    edges: { 
     2: { 
      408868239: {}, 
      843594076: {} 
     } 
    } 
}; 
sys.graft(postLoadData); 

的是,最近的有效JSON可能是:

{ 
    "nodes": { 
     "408868239": { 
      "tipo": "clase", 
      "shape": "dot", 
      "label": "clase2" 
     }, 
     "843594076": { 
      "tipo": "clase", 
      "shape": "dot", 
      "label": "ESTADIA" 
     } 
    }, 
    "edges": { 
     "2": { 
      "408868239": {}, 
      "843594076": {} 
     } 
    } 
} 

你可以使用上面的JSON (不是javascript代碼),然後執行此操作:

JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(theJsonString); 
相關問題