HI @shrisa ,
If I understand the ask correctly. You have a JSON which has all the components data and using that JSON you want to create a page.
If yes, the order of nodes in a JSON object is not guaranteed to be preserved. If maintaining the order is crucial, you should utilize an array to explicitly represent the order.
{
"jcr:primaryType": "cq:Page",
"jcr:content": {
"jcr:primaryType": "cq:PageContent",
"components": [
{ "name": "component1", "sling:resourceType": "your/component/resource/type1", ... },
{ "name": "component2", "sling:resourceType": "your/component/resource/type2", ... },
{ "name": "component3", "sling:resourceType": "your/component/resource/type3", ... }
]
}
}Now, the "components" property is an array, and the order of components in the array will be preserved when you iterate over it.
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONObject;
public class PageCreationService {
public void createPageWithComponents(ResourceResolver resolver, String pagePath, JSONObject json) {
try {
// Get or create the page resource
Resource pageResource = ResourceUtil.getOrCreateResource(resolver, pagePath, "cq:Page", "cq:Page", true);
// Get or create the page content node
Resource contentResource = ResourceUtil.getOrCreateResource(resolver, pagePath + "/jcr:content", "cq:PageContent", "cq:PageContent", true);
// Get the "components" array from the JSON
JSONArray componentsArray = json.getJSONObject("jcr:content").getJSONArray("components");
// Iterate over components array and create components
for (int i = 0; i < componentsArray.length(); i++) {
JSONObject componentJson = componentsArray.getJSONObject(i);
String componentName = componentJson.getString("name");
// Create the component under the page's content node
ResourceUtil.getOrCreateResource(resolver, contentResource.getPath() + "/" + componentName, componentJson);
}
// Commit the changes
resolver.commit();
} catch (Exception e) {
// Handle exceptions appropriately
resolver.refresh();
// Log or handle the exception as needed
} finally {
if (resolver.isLive()) {
resolver.close();
}
}
}
}
Thanks