-
Notifications
You must be signed in to change notification settings - Fork 3
Description
Description:
The SyncStack.setJSON method is incorrectly handling scenarios where the "items" key in the provided JSONObject contains a single item.
Instead of processing this single item, the current logic within the else block (when itemsObj is not a JSONArray) logs a warning and initializes an empty syncItems list, effectively skipping the data.
Code Snippet:
protected synchronized void setJSON(@NotNull JSONObject jsonobject) {
if (jsonobject == null) {
throw new IllegalArgumentException("JSON object cannot be null.");
}
this.receiveJson = jsonobject;
if (receiveJson.has("items")) {
Object itemsObj = receiveJson.opt("items");
if (itemsObj instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) itemsObj;
syncItems = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonItem = jsonArray.optJSONObject(i);
if (jsonItem != null) {
syncItems.add(sanitizeJson(jsonItem));
}
}
} else {
logger.warning("'items' is not a valid list. Skipping processing."); // ✅ Prevent crashes
syncItems = new ArrayList<>();
}
} else {
syncItems = new ArrayList<>();
}
}
Observed Behavior:
When the "items" key in the receiveJson JSONObject contains a single JSON object (not a JSONArray of one element), the code enters the else block and skips processing this item. The syncItems list remains empty in this case.
Expected Behavior:
When the "items" key contains only a single JSON object, it should be treated as a single item to be processed and added to the syncItems list.
Suggested Solution:
The else block should be modified to handle the case where itemsObj is a single JSONObject. A possible solution would be to check if itemsObj is an instance of JSONObject and, if so, create a new ArrayList, add the sanitized itemsObj to it, and assign it to syncItems.
} else {
if (itemsObj instanceof JSONObject) {
syncItems = new ArrayList<>();
syncItems.add(sanitizeJson((JSONObject) itemsObj));
} else {
logger.warning("'items' is not a valid list. Skipping processing."); // ✅ Prevent crashes
syncItems = new ArrayList<>();
}
}
Impact:
This issue leads to data loss or incomplete synchronization when the "items" payload from Contentstack contains a single entry. As there is any exception thrown, we consider the execution as completed, and we are updating the sync token, which leads to data loss.