How to display JSON data through Sling Model

Avatar

Avatar

ashwinikhaple

Avatar

ashwinikhaple

ashwinikhaple

06-04-2021

I have created a Component that has title, description, date, URL, and read the values in SlingModel then how can I display the data in the form of JSON to the frontend through the sling model?

Accepted Solutions (1)

Accepted Solutions (1)

Avatar

Avatar

asutosh_j3

Avatar

asutosh_j3

asutosh_j3

06-04-2021

Hi @ashwinikhaple 
If there is a sling model available and you want to fetch the same properties as a JSON response,so there is no need to create a Sling Servlet. You just need to export your sling model using jackson exporter and that’s all. Sling Model Exporter can be used as a web service or as a rest API.

 

Sling Model Exporter was introduced in Sling Models v1.3.0 which allows new annotations to be added to Sling Models that define how the Model an can be exported as a different Java object, or more commonly, serialized into a different format such as JSON.

 

@Model(adaptables = Resource.class, resourceType = { "wknd/components/content/image" }, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
@Exporter(name = "jackson", extensions = "json", options = { @ExporterOption(name = "SerializationFeature.WRITE_DATES_AS_TIMESTAMPS", value = "true") })
public class ModelComponent {

@Inject
String title;

@Inject
String description;

@Inject
String date;

@Inject
String URL;

@Inject
@Named("sling:resourceType")
String slingResourceType;

public String getDescription() {
return description;
}

public String getDate() {
return date;
}

public String getURL() {
return URL;
}

public String getSlingResourceType() {
return slingResourceType;
}

public String getTitle() {
return title;
}
}

 

Please refer the below article:

https://experienceleague.adobe.com/docs/experience-manager-learn/foundation/development/develop-slin...

http://www.sgaemsolutions.com/2017/06/sling-model-exporter-in-aem-63.html

 

Hope this helps!

Thanks!