[英]Java: Append key value pair to nested json object
我得到了三個輸入。
一個 JSON 對象(嵌套)
一個節點結構
我的任務是通過查看節點結構並更新原始 JSON 來將鍵值對附加到節點。
例如,如果輸入是,
JSON 對象
{ a: { b: { c:{} } } }
節點結構
ab
鍵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{ } } } }
我被困在這里。 請幫忙。 提前致謝。
可以使用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.