0

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?

dzenisiy
  • 855
  • 10
  • 32

1 Answers1

4

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.

Sharath Madappa
  • 3,393
  • 1
  • 24
  • 41
  • Also I added selector configuration @Exporter(name = "jackson", extensions = "json", selector = ""), to have request without selector. Thank you a lot – dzenisiy Aug 24 '18 at 09:15
  • @cylinder.y not having a selector can lead to un-expected behaviour. AEM uses the json output for rendering dialogs etc.. by sending processed response instead of dump of resource/properties will break such functionality – Sharath Madappa Aug 24 '18 at 09:29
  • but this model only used for representing JSON response, this resource-type doesn't have any configuration – dzenisiy Aug 24 '18 at 10:16