我嘗試刪除任意JSON的所有節點,其值爲'null'。在java中刪除JSON節點
不知怎的,我與JsonPath掙扎因此,我試圖通過JSON用下面的代碼迭代:
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
if(value.toString().equalsIgnoreCase("NULL")) {
object.remove(key);
}
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
當我運行它在我的JSON,然後再不是整個元素被刪除,因爲支架留。我還想知道,如果它能起作用,如果我在兩個不同的地方有同樣的密鑰名稱,但只想刪除一個。
之前:{ 「利益」:[{ 「interestKey1」: 「狗」},{ 「interestKey2」: 「貓」},{ 「interestKey3」:空}]}
後:{ 「interest」:[{「interestKey1」:「Dogs」},{「interestKey2」:「Cats」},{}]}
我應該如何處理?