如何将多个 JSON 字符串合并为一个 ( Java )

How do you combine multiple JSON strings into one ( Java )

我尝试搜索可以使用的 JAVA 库,但无济于事。 是否有一个 gson/jackson/groovy 库可以用来将多个 JSON 字符串组合或合并到一个有效负载中?

示例: JSON 负载 A、B 和 C

我希望 B 和 C 都成为 A 的 added/merged。

同时删除所有为空或空的重复键。

示例:

  1. 第一个 JSON :
{
   "businessUnitHierarchies":[
      {
         "actionType":"sample123",
         "businessUnitHierarchy":{
            "businessUnit":"sample123"
         }
      }
   ],
   "description":{
      "EN":"description sample",
      "FR":"sample de description"
   },
   "name":{
      "EN":"Coupon by a bot",
      "FR":"Coupon par un bot"
   },
   "discountType":"Cost+",
   "quantity":0,
   "usageType":"shared",
   "notes":"sample notes",
   "discounts":[
      {
         "discountLevel":"SAMPLE",
         "discountAmount":"10"
      }
   ],
   "couponId":0
}
  1. 第二个JSON:

    {
       "effectiveDate":"2020-09-10",
       "expiryDate":"2020-09-11",
       "quantity":0,
       "couponId":0
    }
  1. 第三个JSON
    {
   "productHierarchies":[
      {
         "productHierarchy":{
            "level":7
         },
         "businessUnit":"fgl",
         "actionType":"include",
         "brand":"SAMPLE",
         "discountAmount":"35"
      }
   ],
   "quantity":0,
   "couponId":0
}

我想要的输出是:

期望的输出:

{
   "businessUnitHierarchies":[
      {
         "actionType":"sample123",
         "businessUnitHierarchy":{
            "businessUnit":"sample123"
         }
      }
   ],
   "description":{
      "EN":"description sample",
      "FR":"sample de description"
   },
   "name":{
      "EN":"Coupon by a bot",
      "FR":"Coupon par un bot"
   },
   "discountType":"Cost+",
   "quantity":0,
   "usageType":"shared",
   "notes":"sample notes",
   "discounts":[
      {
         "discountLevel":"SAMPLE",
         "discountAmount":"10"
      }
   ],
   "couponId":0,
      "effectiveDate":"2020-09-10",
   "expiryDate":"2020-09-11",
   "quantity":0,
   "productHierarchies":[
      {
         "productHierarchy":{
            "level":7
         },
         "businessUnit":"fgl",
         "actionType":"include",
         "brand":"SAMPLE",
         "discountAmount":"35"
      }
   ]
}

这难道不是你想要的吗?基于 Gson.

void merge(JsonObject dest, JsonObject src) {
    for (var entry : src.entrySet()) {
        dest.add(entry.getKey(), entry.getValue();
    }
}