将多个JSONArray中的JSONObject组合为Java中的单个JSONArray

时间:2018-07-27 03:19:17

标签: java json java-8

我有3个JSONArray,如下所示。

RegionArray:

[  
   {  
      "catalog_product_id":620,
      "region_id":"en_US"
   },
   {  
      "catalog_product_id":40078,
      "region_id":"en_US"
   },
   {  
      "catalog_product_id":1048,
      "region_id":"en_US"
   }
]

CountryArray:

[  
   {  
      "catalog_product_id":620,
      "country_id":"DE"
   },
   {  
      "catalog_product_id":40078,
      "country_id":"DE"
   }
]

CompanyArray:

[
    {  
          "company_id":706,
          "catalog_product_id":40078
       },
       {  
          "company_id":706,
          "catalog_product_id":1048
       }
    }
]

这3种不同的JSONArray正在合并为单个JSONArray,并获得如下所示的结果。我通过将所有JSONObjects添加到单个公共数组中来制作此数组。JSONArray.put(regionJSONObj);JSONArray.put(countryJSONObj);JSONArray.put(companyJSONObj);

[  

    {  
      "catalog_product_id":620,
      "region_id":"en_US"
   },
   {  
      "catalog_product_id":40078,
      "region_id":"en_US"
   },
   {  
      "catalog_product_id":1048,
      "region_id":"en_US"
   },
   {  
      "catalog_product_id":620,
      "country_id":"DE"
   },
   {  
      "catalog_product_id":40078,
      "country_id":"DE"
   },
   {  
      "company_id":706,
      "catalog_product_id":40078
   },
   {  
      "company_id":706,
      "catalog_product_id":1048
   }

]

来自所有3个源JSONArray catalog_product_id的键在所有3个JSONArray中都相同。因此,我想像以下格式那样构建目标JSONArray。

[
    {
         "catalog_product_id":620,
         "region_id":"en_US",
         "country_id":"DE",
    },
    {
         "catalog_product_id":40078,
         "region_id":"en_US",
         "country_id":"DE",
         "company_id":706,
    },
    {
         "catalog_product_id":1048,
         "region_id":"en_US",
         "company_id":706

    }

]

所有3个JSONArray RegionArrayCountryArrayCompanyArray具有公用密钥catalog_product_id。所以我想将catalog_product_id与所有3个JSONArray进行匹配,并获取regioncountrycompany信息,并为该特定catalog_product_id生成单个对象

1 个答案:

答案 0 :(得分:0)

Map<String, JArray> map = 
jArrayLis.stream().collect(Collectors.toMap(JArray::getCatalog_product_id, 
Function.identity()));