How do I get the JSON from a Sling Model programmatically?

jkpanera

01-07-2019

Hey guys,

So I have a number of sling models that I have JSON exporters for. Like so:

@Getter
@Model(adaptables = {SlingHttpServletRequest.class, Resource.class},
   defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL,
   resourceType = "components/component2")

@Exporter(name = "jackson", extensions = "json", options = {

   @ExporterOption(name = "SerializationFeature.FAIL_ON_EMPTY_BEANS", value = "false")

})

public class Component2 {

  @ValueMapValue
  private boolean value1;

}

@Getter
@Model(adaptables = {SlingHttpServletRequest.class, Resource.class},
   defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL,
   resourceType = "components/component1")

@Exporter(name = "jackson", extensions = "json", options = {

   @ExporterOption(name = "SerializationFeature.FAIL_ON_EMPTY_BEANS", value = "false")

})

public class Component1 {

@Self
  @JsonIgnore
  private SlingHttpServletRequest request;

  @SlingObject
  @JsonIgnore
  private Resource resource;

  @ValueMapValue
  private String localizedModelProperty1;
  @ValueMapValue
  private AlertMapping localizedModelProperty2;

  @PostConstruct
  protected final void init() {

     Resource resource = getJCRResourceForComponent2();

     Component2 component2 = resource.adaptTo(Component2.class);

  }

}

Now I would like to be able to get the JSON for component2 in component1. I have the resource and I've adapted it to the model. Is there a way to do that?

Thanks!