2

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?

Oliver Gebert
  • 1,166
  • 1
  • 6
  • 20

1 Answers1

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.

Oliver Gebert
  • 1,166
  • 1
  • 6
  • 20