@navjots90210021,
Apache Sling Models currently includes a single exporter, using the Jackson framework, which is capable of serializing models as JSON. Adobe's new core components are built with Sling Models, meaning that if you can easily build a headless AEM solution only using the core components. If you are using Adobe's core page component, and editable templates, you can replace ".html" with ".model.json", and you will get a JSON representation of the page structure (resourceType & all used components); assuming that you're Apache Dispatcher module rules allow you to access .model.json. e.g: https://example.com/home.model.json
Then there's no magic happening with the Jackson Exporter; all getter properties of your Sling Models class will exposed, and serialized to JSON. This means that if you run some kind of logic in your @PostConstruct method, then set the property, the computed value will be exposed in your JSON.
Take the example below:
@Model(adaptables = Resource.class,
resourceType = ComponentExample.RESOURCE_TYPE,
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
@Exporter(name = ExporterConstants.SLING_MODEL_EXPORTER_NAME, extensions = ExporterConstants.SLING_MODEL_EXTENSION)
public class ComponentExample {
protected static final String RESOURCE_TYPE = "my-site/components/content/componentexample";
@ScriptVariable
private Page currentPage;
private String pagePath;
private String logicTitle;
@PostConstruct
public void init() {
if (YOUR_CONDITIONAL_LOGIC_GOES_HERE) {
pagePath = currentPage.getPath();
setLogicTitle();
}
}
private void setLogicTitle() {
// logic goes here
logicTitle = "results";
}
public String getPagePath() {
return pagePath;
}
public String getLogicTitle() {
return logicTitle;
}
}
When you append ".model.json" to your page (created with Adobe core components), if you have this component exist on the page && if YOUR_CONDITIONAL_LOGIC_GOES_HERE == true, then you will see the JSON response is:
{
pagePath: 'path of page',
logicTitle: results',
}
I can't stress to always add unit tests with your Sling Models. A great example that I like to share is this example - https://sourcedcode.com/aem-sling-models-unit-test-junit-4-with-examples
I hope this helps,
Brian.