Input
{
"email" : "[email protected]"
},{
"email" : "[email protected]"
},{
"email" : "[email protected]"
},{
"email" : "[email protected]"
},
Expected output
{
"email" : "[email protected]"
},{
"email" : "[email protected]"
},
Remove duplicates
maintain format
appended last comma.
The problem is sometimes the input is not a proper JSON and also it's not sure that comma should be always present at the end. I need to remove only duplicate key value pairs from the input, the rest should remain the same.
I tried this way.
if (maxIndex > 0) {
try {
singleElementTemplate = dao.resolveObjectDataStringSinglePass(tmdtId, sourceTagHandle,
maxIndex);
String jsonText = singleElementTemplate.trim();
if (!jsonText.startsWith("[") && !jsonText.endsWith("]")) {
jsonText = "[" + jsonText + "]";
}
JSONArray jsonArr = new JSONArray(jsonText);
Set<String> seen = new LinkedHashSet<>();
JSONArray finalJsonArr = new JSONArray();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject obj = jsonArr.getJSONObject(i);
if (seen.add(obj.toString())) {
finalJsonArr.put(obj);
}
}
StringBuilder formattedResult = new StringBuilder();
for (int i = 0; i < finalJsonArr.length(); i++) {
// Appends formatted JSON (2-space indent)
formattedResult.append(finalJsonArr.getJSONObject(i).toString(2));
if (i < finalJsonArr.length() - 1) {
formattedResult.append(",\n");
}
}
singleElementTemplate = formattedResult.toString().trim();
} catch (JSONException ex1) {
}
} else {}
But the output is like this.
{"email" : "[email protected]"},
{"email" : "[email protected]"}
Note: I can't use regex as the JSON could also contain nested {}.