[英]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.