英文:
Remove all keys except one from JSONObject
问题
{
"a": "a"
}
英文:
I have a JSONObject (org.json) like this:
{
"a": "a",
"b": "a",
"c": "a",
"d": "a",
"e": "a",
"f": "a",
"g": "a",
...
}
I would like to remove all the keys except a
. Is there an elegant way to do this other than my naive approach?
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
if (!keys.next().equals("a")) {
keys.remove();
}
}
Expected output:
{"a": "a"}
答案1
得分: 4
我认为更简单的方法是使用 removeIf
,如下所示:
jsonObject.keySet().removeIf(k -> !k.equals("a"));
英文:
I believe a simpler way to do that would be using removeIf
as
jsonObject.keySet().removeIf(k -> !k.equals("a"));
答案2
得分: 3
以下是您要翻译的内容:
不使用 Gson,以下是一种减少代码行数的方式,但我不太喜欢使用 ArrayList 来创建键的副本以防止 ConcurrentModificationException。老实说,您的代码已经不错了。
new ArrayList<>(object.keySet())
.stream()
.filter(key -> !key.equals("a"))
.forEach(object::remove);
甚至我会声明一个 List,将它变成 2 行,因为那个可怕的 new ArrayList 调用。
List<String> keysForRemoval = object.keySet()
.stream()
.filter(key -> !key.equals("a"))
.collect(Collectors.toList());
keysForRemoval.forEach(object::remove);
英文:
Without using Gson, this is one way that you could reduce the line count but i'm not a huge fan of using ArrayList to create a copy of the keys to prevent a ConcurrentModificationException. Honestly, what you have isn't bad.
new ArrayList<>(object.keySet())
.stream()
.filter(key -> !key.equals("a"))
.forEach(object::remove);
I would even declare the List and make it 2 lines because of that horrid new ArrayList call.
List<String> keysForRemoval = object.keySet()
.stream()
.filter(key -> !key.equals("a"))
.collect(Collectors.toList());
keysForRemoval.forEach(object::remove);
答案3
得分: 2
你考虑过使用所需的键创建一个新对象吗?
jsonObject = new JSONObject().put("a", jsonObject.get("a"));
英文:
Did you consider creating a new object with the required key?
jsonObject = new JSONObject().put("a", jsonObject.get("a"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论