删除java中的JSON节点
我尝试删除任意JSON的所有节点,这些节点的值为“null” 不知何故,我在使用JsonPath时遇到了困难,因此我尝试使用以下代码迭代JSON:删除java中的JSON节点,java,json,Java,Json,我尝试删除任意JSON的所有节点,这些节点的值为“null” 不知何故,我在使用JsonPath时遇到了困难,因此我尝试使用以下代码迭代JSON: public static Map<String, Object> toMap(JSONObject object) throws JSONException { Map<String, Object> map = new HashMap<String, Object>(); Iterator&l
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上运行它时,并不是整个元素都会被删除,因为括号会保留下来。我还想知道,如果我在两个不同的地方有相同的密钥名称,但只想删除一个,这是否有效
之前:{interest:[{interestKey1:Dogs},{interestKey2:Cats},{interestKey3:null}]}
之后:{兴趣:[{interestKey1:Dogs},{interestKey2:Cats},{}]}
我应该如何处理这个问题?您正在从JsonObject中删除键值对,而不是封闭的JsonArray。JsonObject本身可以有多个键值对。因此,删除一个对象并不会删除整个对象
jsonObj={"a":"cde","b":"fgh"}
这是一个有效的jsonObject。当我像jsonObj.removeb一样从中删除b时,只剩下a{a:cde},删除a返回{}
因此,如果要从jsonArray中删除整个jsonObject,请直接从jsonArray中删除它
在JsonArray中,您不能选择带有键的jsonObject,而是选择带有索引的jsonObject。因此,即使它有两个具有相同键的JSONObject,您也必须根据它们的唯一索引选择一个。尝试处理对象的基本大小写。 下面的代码可能会有所帮助:
public static Map<String, Object> toMap(JSONObject object) throws
JSONException {
if(object==null)return null;
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);
}
if(null != value)
map.put(key, value);
if(null==value || value.toString().equalsIgnoreCase("NULL")) {
object.remove(key);
}
}
return map;
}