aem - 如何将 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>
有没有不创建组件的优雅解决方案?
解决方案
如果您使用的是 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
您可以通过注释中的配置将选择器覆盖为“模型”之外的其他东西。
推荐阅读
- json - firebase 可以自行更新吗?
- kotlin - 如何在 Kotlin Multiplatform 中使用 BigDecimal?
- wordpress - 谷歌地图与wordpress中的联系信息
- java - 在 JAVA 8 中避免 ConcurrentModificationException 的最佳方法是什么
- java - 在循环中使用 Nodelist 解析 XML
- json - 如何在网页上使用 Rest
- python-3.x - 如何选择最重要的特征?特征工程
- eclipse - 如何在 IntelliJIDEA 中创建动态 Web 项目
- c# - WPF TreeView DataTemplate 绑定与非嵌套类问题
- angular - 角度 - 在构建的资产文件夹中更改数据