首页 > 解决方案 > 如何将 Sling 模型导出为 JSON 并将其呈现给最终用户?

问题描述

假设我有以下模型:

@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;
   ........

如何将此模型作为 JSON 呈现给最终用户?

我知道可以使用GSON库将 java 类转换为 JSON,但在这种情况下,我应该引入新字段并在 @PostConstruct 方法中对其进行初始化:

private String json;

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

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

而不是在 html 中使用这个模型(需要新创建组件)

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

有没有不创建组件的优雅解决方案?

标签: aemslingsling-models

解决方案


如果您使用的是 6.3 +,则可以使用 sling 模型导出器功能来执行此操作,

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

将您的代码更改为

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

请求<path-to-resource>.model.json将以 JSON 格式返回模型。Exporter您可以通过注释中的配置将选择器覆盖为“模型”之外的其他东西。


推荐阅读