aemslingsling-models

How to export Sling Model into JSON and render it to end user?


Let's assume I have the following model:

@Model(adaptables = Resource.class)
public class BasicScheduleModel {
   @Self
   protected Resource resource;
   protected Envelope envelope;
   protected Status status;
   protected Metadata metadata;
   protected Data data;
   protected Messages messages;
   ........

How can I render this model to end user as a JSON?

I know that it is possible to convert java class to JSON using GSON library, but in this case I should introduce new field and initialize it in @PostConstruct method:

private String json;

@PostContruct
private void init() {
    this.json = new GsonBuilder().create().toJson(this);
}

private String getJson() {
    return this.json;
}

And than use this model in html using sightly(it is necessary to new create component)

<sly data-sly-use.model="com.somewebsite.models.BasicScheduleModel">
${model.json @ context='unsafe'}
</sly>

Is there an elegant solution without of component creating?


Solution

  • If you are on 6.3 + you can use the sling model exporter feature to do this,

    https://sling.apache.org/documentation/bundles/models.html#exporter-framework-since-130-1

    Change your code to

    @Model(adaptable = Resource.class, resourceType = "<resourcetype-here>") 
    @Exporter(name = "jackson", extensions = "json")
    

    Requests to <path-to-resource>.model.json will return the model in JSON format. You can override the selector to be something else apart from 'model' via configurations in Exporter annotation.