【问题标题】:Java: How to add a JSON object to a JSON array only if one of the elements don't already existJava:仅当其中一个元素尚不存在时,如何将 JSON 对象添加到 JSON 数组
【发布时间】:2018-11-26 21:16:18
【问题描述】:

假设我有一个 JSON 对象的 JSON 数组(在 JSON 对象内部)。

{
  data:
    [
      {id:45, building:1, lane: 6},
      {id:58, building:1, lane: 9},
      {id:46, building:2, lane: 4},
      {id:51, building:2, lane: 9},
      {id:40, building:3, lane: 2},
      {id:39, building:4, lane: 3}
  ]
}

我想循环遍历数组并将每个 JSON 对象添加到新的 JSON 数组中,但前提是某个键 (building) 的值之一尚未添加到新的 JSON 数组中。

例如,如果我遍历 JSON 数组并到达 id:45,我想将该对象添加到我的新 JSON 数组中,但前提是尚不存在具有 @ 键值对的对象987654325@。因为它是第一个对象,所以它会被添加到新数组中。

假设我迭代的第二个对象是id:58。由于我的新 JSON 数组已经有一个带有 building:1 的对象,我不想将该对象添加到我的新数组中。

我该怎么做呢?

【问题讨论】:

  • 您是否尝试过自己的任何方法,以便我们检查并提供一些解决方案?
  • 当然。我会更新的。
  • 你应该使用 HashSet 来存储你的数据,使用 id 作为键以避免重复,关于 json 迭代检查这个例子edureka.co/community/7982/iterate-over-a-jsonobject

标签: java arrays json key-value


【解决方案1】:

我自己没有对此进行测试,但它应该可以工作。

    JSONArray arr = //your data object
    JSONArray newArr = new JSONArray();
    arr.stream().forEach(el -> {
        Integer val = (Integer) ((JSONObject) el).get("building");
        if (((List<Integer>) newArr.parallelStream().map(obj -> (Integer) ((JSONObject) obj).get("building"))
                .filter(obj -> obj == val).collect(Collectors.toList())).isEmpty()) {
            newArr.add(el);
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 2018-09-29
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多