Get .model.json as String

六眼飞鱼酱① 提交于 2021-02-08 04:59:24

问题


I wonder if there is an easy way to get a String with the result of a sling content exporter in AEM. In my current usecase I need the content of a component's .model.json output in the component's htl file and sending an additional request is obviously not a good idea. Any hints on how I can get the data?


回答1:


After some reading and experimenting, I found a way to do it:

Add a dependency to the following package in your pom:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.5</version>
    </dependency>

Then create a method in your model that does the serialization:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public String getJson() {
    ObjectMapper objectMapper = new ObjectMapper();
    String tStr = "";
    try {
        tStr = objectMapper.writeValueAsString(this);
        logger.error(tStr);
    }
    catch (JsonProcessingException ex) {
        logger.error("Cannot do it: {}", ex.getMessage());
    }
    return tStr;
}

Now you can call this method from inside a HTL script or any other code fragment that has access to the model.



来源:https://stackoverflow.com/questions/57527180/get-model-json-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!