从JSONObject中删除除一个之外的所有键。

huangapple go评论81阅读模式
英文:

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&lt;&gt;(object.keySet())
                    .stream()
                    .filter(key -&gt; !key.equals(&quot;a&quot;))
                    .forEach(object::remove);

I would even declare the List and make it 2 lines because of that horrid new ArrayList call.

            List&lt;String&gt; keysForRemoval = object.keySet()
                    .stream()
                    .filter(key -&gt; !key.equals(&quot;a&quot;))
                    .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(&quot;a&quot;, jsonObject.get(&quot;a&quot;));

huangapple
  • 本文由 发表于 2020年4月5日 09:30:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/61036956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定