You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Sling模型中排除组件对话框未编辑的JSON标签字段

在AEM Sling模型中排除未编辑字段的JSON输出

针对组件对话框中未编辑的标签页字段,要在model.json中移除对应null值的节点,可以通过以下两种Sling模型实现方式:

方法一:基于子模型+Jackson注解控制序列化

1. 定义标签页子模型

创建对应标签页的子模型类,包含字段注入和内容有效性判断:

public class TabModel {
    @ValueMapValue
    private String field;

    public String getField() {
        return field;
    }

    // 判断当前标签页是否有已编辑的有效值
    public boolean hasContent() {
        return field != null && !field.isBlank();
    }
}

2. 主组件模型中控制序列化

在主模型中注入子模型,通过@JsonInclude注解指定只序列化非空属性,同时在getter方法中判断标签页是否有内容:

@Model(adaptables = Resource.class, resourceType = "your/project/components/your-component")
@JsonInclude(JsonInclude.Include.NON_NULL) // 忽略值为null的属性
public class ComponentModel {
    @Inject
    private TabModel a;

    @Inject
    private TabModel b;

    public TabModel getA() {
        return (a != null && a.hasContent()) ? a : null;
    }

    public TabModel getB() {
        return (b != null && b.hasContent()) ? b : null;
    }
}

当标签页无有效值时,对应getter返回null,@JsonInclude(NON_NULL)会自动将该属性从JSON输出中排除。

方法二:直接构建JSON返回Map

通过@JsonValue注解直接返回自定义构建的Map,仅包含有编辑值的标签页:

@Model(adaptables = Resource.class, resourceType = "your/project/components/your-component")
public class ComponentModel {
    @ValueMapValue(name = "a/field")
    private String aField;

    @ValueMapValue(name = "b/field")
    private String bField;

    @JsonValue
    public Map<String, Object> getComponentJson() {
        Map<String, Object> resultMap = new HashMap<>();

        // 仅当a标签页字段有值时加入
        if (aField != null && !aField.isBlank()) {
            Map<String, String> aTab = new HashMap<>();
            aTab.put("field", aField);
            resultMap.put("a", aTab);
        }

        // 仅当b标签页字段有值时加入
        if (bField != null && !bField.isBlank()) {
            Map<String, String> bTab = new HashMap<>();
            bTab.put("field", bField);
            resultMap.put("b", bTab);
        }

        return resultMap;
    }
}

这种方式更灵活,可直接控制每个标签页是否出现在最终JSON中,无需依赖Jackson注解配置。


内容的提问来源于stack exchange,提问作者Bhavik Kothari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:22:54