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

Avatar

Avatar

jkpanera

Avatar

jkpanera

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!

Accepted Solutions (1)

Accepted Solutions (1)

Avatar

Avatar

Jörg_Hoh

Employee

Total Posts

3.0K

Likes

953

Correct Reply

1.0K

Avatar

Jörg_Hoh

Employee

Total Posts

3.0K

Likes

953

Correct Reply

1.0K
Jörg_Hoh
Employee

02-07-2019

Check the first paragraph of the Sling documentation [1].

[1] Apache Sling :: Sling Models

Answers (2)

Answers (2)

Avatar

Avatar

jkpanera

Avatar

jkpanera

jkpanera

02-07-2019

For a component.

Avatar

Avatar

Prince_Shivhare

Avatar

Prince_Shivhare

Prince_Shivhare

02-07-2019

Hi,

Can you please clarify here. you want a JSON for a Component or Content page?