Given this JSON:
{
"contact_data": [
"address/all",
"telephone/us"
],
"financial_data": [
"bank_account_number/all",
"bank_account_number/uk",
"credit_card_numbers"
]
}
and this JSON:
{
"financial_data": [
"credit_card_numbers",
"bank_account_number/ca",
"bank_account_number/all"
],
"government_id": [
"driving_license/americas"
],
"sensitive_data": [
"racial_ethnic_origin"
]
}
I want to merge these to look like this:
{
"contact_data": [
"address/all",
"telephone/us"
],
"financial_data": [
"credit_card_numbers",
"bank_account_number/ca",
"bank_account_number/uk",
"bank_account_number/all"
],
"government_id": [
"driving_license/americas"
],
"sensitive_data": [
"racial_ethnic_origin"
]
}
I have the following, which almost works:
import org.json.JSONObject;
...
final List<String> jsonStrings = ...; // A list of the above sample JSONs
final List<JSONObject> jsonObjects = jsonStrings
.stream()
.map(JSONObject::new)
// JSONObject.getNames() (called later on) will return null if JSONObject is empty, so filter out empty objects.
.filter(jsonObject -> !jsonObject.isEmpty())
.collect(Collectors.toList());
if (jsonObjects..size() > 1) {
// Merge multiple JSONObjects: https://stackoverflow.com/a/2403453/12177456
final JSONObject firstJsonObject = jsonObjects.get(0);
final JSONObject merged = new JSONObject(firstJsonObject, JSONObject.getNames(firstJsonObject));
final List<JSONObject> remainingJsonObjects = jsonObjects.subList(1, jsonObjects.size());
for (final JSONObject nextJsonObject : remainingJsonObjects) {
for (final String nextJsonObjectFieldName : JSONObject.getNames(nextJsonObject)) {
merged.put(nextJsonObjectFieldName, nextJsonObject.get(nextJsonObjectFieldName));
}
}
return merged;
}
however, where I would expect to see 4 entries in financial_data
:
...
"financial_data": [
"bank_account_number/all",
"bank_account_number/uk",
"bank_account_number/ca",
"credit_card_numbers"
]
...
instead, I see just 3, with bank_account_number/uk
not in the merged result:
...
"financial_data": [
"bank_account_number/all",
"bank_account_number/ca",
"credit_card_numbers"
]
...
I'm not stuck on using org.json
, if it's simplier using gson, jackson, plain Java maps, I'm ok with that.