Expose JSON for All Components in AEM Page
2)
2)
Hi @sku4 ,
Your Core Challenge:
You're using:
modelFactory.createModel(res, Object.class);
which doesn’t dynamically resolve to the specific Sling Model of the component. This happens because Object.class is not a base type Sling Model can resolve to. Sling doesn’t know what model to adapt to unless a class is explicitly defined or the model is marked with an interface.
Solution: Use a Common Interface for Your Component Models
Define a base interface (e.g., ComponentExporterModel) for all your component Sling Models.
public interface ComponentExporterModel {
// marker interface, or add common getters if needed
}
Update your component models to implement this interface:
@Model(adaptables = Resource.class,
resourceType = "project/components/mycomponent",
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL,
adapters = ComponentExporterModel.class)
@Exporter(name = "jackson", extensions = "json")
public class MyComponentModel implements ComponentExporterModel {
@Inject
@JsonProperty
private String title;
}
In your PageModel, change this:
Object model = modelFactory.createModel(res, Object.class);
To this:
if (modelFactory.canCreateFromAdaptable(res, ComponentExporterModel.class)) {
ComponentExporterModel model = modelFactory.createModel(res, ComponentExporterModel.class);
String jsonString = modelFactory.exportModel(model, "jackson", String.class, null);
return new JSONObject(jsonString);
}
Benefits of This Approach:
Scalable: You don't have to update your PageModel when new components are added.
Cleaner JSON: No OOTB junk like cq:allowedComponents.
Reusable: Component models stay modular.
Secure: Only models implementing your interface are exported.
Regards,
Amit
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.