从JSONObjects的JSONArray中删除除一个元素外的所有元素 [英] Remove all elements except one from JSONArray of JSONObjects
问题描述
我有这样的JSONArray(org.json):
I have a JSONArray (org.json) like this:
[
{ "a": "a" },
{ "b": "a" },
{ "c": "a" },
{ "d": "a" },
{ "e": "a" },
{ "f": "a" },
{ "g": "a" }
]
我想删除所有不要<的 JSONObject
/ strong>使用键 a
。除了我的幼稚方法外,还有其他更好的方法吗?
I would like to remove all the JSONObject
s that do not have the key a
. Is there a better way to do other than my naive approach?
Iterator objects = jsonArray.iterator();
while (objects.hasNext()) {
Object o = objects.next();
if (o instanceof JSONObject && !((JSONObject) o).has("a")) {
objects.remove();
}
}
预期输出:
[{"a": "a"}]
推荐答案
如果您正在寻找一种功能样式的解决方案,则可以将 Iterator
包装到 Stream
,然后做任何您想做的事情。
If you're seeking a functional style solution, you can wrap the Iterator
into a Stream
and then do whatever you want.
一种功能解决方案:
JSONArray newJsonArray =
StreamSupport.stream(jsonArray.spliterator(), false)
.filter(JSONObject.class::isInstance)
.map(JSONObject.class::cast)
.filter(j -> j.has("a"))
.collect(collectingAndThen(toList(), JSONArray::new));
注意:以上解决方案不会修改原始的 JSONArray
。遵循函数式编程的原理,应该更喜欢将其收集到一个新对象中,而不是修改现有对象。
Note: The solution above does not modify the original JSONArray
. Following the principles of functional programming one should prefer collecting into a new object rather than modifying the existing one.
这篇关于从JSONObjects的JSONArray中删除除一个元素外的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!