简体   繁体   English

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

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

I tried searching for a JAVA library that I could use but to no avail.我尝试搜索可以使用的 JAVA 库,但无济于事。 Is there a gson/jackson/groovy library I could use to combine or merge together multiple JSON Strings into one payload?是否有一个 gson/jackson/groovy 库可以用来将多个 JSON 字符串组合或合并到一个有效负载中?

Example : JSON payload A, B and C示例:JSON 负载 A、B 和 C

I would like both B and C to be added/merged to A.我希望 B 和 C 都添加/合并到 A。

Also removing any duplicated keys that are null or empty.还删除任何为空或空的重复键。

Example :例子 :

  1. First JSON :第一个 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. Second JSON :第二个 JSON :

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

My desired output is :我想要的输出是:

Desired Output :期望输出:

{
   "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"
      }
   ]
}

Wouldn't this be all you want?这不就是你想要的吗? Based on Gson .基于Gson

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM