[英]Remove entries from JSONArray Java
我有以下json:
{
"scenes": {
"A-B-C": [{
"id": "OPENINGS",
"value": "A"
},
{
"id": "VIEW",
"value": "B"
},
{
"id": "CAMERA",
"value": "C"
},
{
"id": "VIEW",
"value": "D" //this should be removed
},
{
"id": "CAMERA",
"value": "E" //this should be removed
}
],
"A-D-E": [{
"id": "OPENINGS",
"value": "A"
},
{
"id": "VIEW",
"value": "B" //this should be removed
},
{
"id": "CAMERA",
"value": "C" //this should be removed
},
{
"id": "VIEW",
"value": "D"
},
{
"id": "CAMERA",
"value": "E"
}
]
}
}
我的目標是從兩個數組中的每個數組中刪除“值”鍵中的值未出現在父鍵中的條目。 我正在使用以下Java代碼:
Set<String> keys = modelJSON.getJSONObject("scenes").keySet();
List<Integer> remove = new ArrayList<Integer>();
for (String keyValue : keys) {
JSONArray array = modelJSON.getJSONObject("scenes").getJSONArray(keyValue);
remove.clear();
int l = array.length();
for (int i = 0; i < l; i++) {
String target = modelJSON.getJSONObject("scenes").getJSONArray(keyValue).getJSONObject(i).getString("value");
if (!keyValue.contains(target)) {
remove.add(i);
}
}
Collections.sort(remove, Collections.reverseOrder());
for (int j : remove) {
array.remove(j);
}
modelJSON.getJSONObject("scenes").put(keyValue, array);
}
在調試器中,我看到代碼可以完美運行到最后一行。 array
變量恰好包含執行最后一行之前我需要的條目。 問題是,隨着put
函數的執行,新的數組將在每個父鍵中替換。 導致此結果:
{
"scenes": {
"A-B-C": [{
"id": "OPENINGS",
"value": "000002_01"
}],
"A-D-E": [{
"id": "OPENINGS",
"value": "000002_01"
}]
}
}
有人可以猜測發生了什么嗎?
array.remove(j);
本身不會更改您的JSON數據。 就個人而言,我看不到此array
變量的用途。
由於JSON不能有重復的鍵,因此當您put(keyValue, array)
,它將覆蓋舊值。 嘗試調試代碼以觀察該數組縮小。
您似乎想要放置remove
列表。
制作一個新的JSONArray,並向其添加modelJSON.getJSONObject("scenes").getJSONArray(keyValue).getJSONObject(i)
。 然后把那個
像這樣
JSONArray newArray = new JSONArray();
JSONObject scenes = modelJSON.getJSONObject("scenes");
JSONArray array = scenes.getJSONArray(keyValue);
for (int i=0; i<array.length();i++){
JSONObject target = array.getJSONObject(i);
if (!keyValue.contains( target.getString("value")) ){
newArray.put(target);
}
}
scenes.put(keyValue, newArray);
// modelJSON.put("scenes", scenes); // maybe necessary
基本上,執行相反的操作-不要刪除,而是添加要查看的數據並覆蓋以前的數據
只需從JSONArray中刪除該位置
array.remove(position) notifyDataSetChanged()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.