How to create JSON file in AEM/Adobe CQ5 Repository

Sample Java code Snippet

Resource metadataOptionJson = ResourceUtil.getOrCreateResource(
resolver,
parentPath+ "/sample.json",
Collections.singletonMap("jcr:primaryType",(Object) "nt:file"),
null, false);
Resource metadataOptionJsonJcrContent = ResourceUtil.getOrCreateResource(
resolver,
metadataOptionJson.getPath() + "/jcr:content",
Collections.singletonMap("jcr:primaryType",(Object) "nt:resource"),
null, false);

final ModifiableValueMap metadataOptionJsonProprties = metadataOptionJsonJcrContent.adaptTo(ModifiableValueMap.class);
if (metadataOptionJsonProprties.get("jcr:data") != null) {
// Remove the property first in case Types differ
metadataOptionJsonProprties.remove("jcr:data");
}

metadataOptionJsonProprties.put("jcr:mimeType", "application/json");
metadataOptionJsonProprties.put("jcr:encoding", "utf-8");
final ByteArrayInputStream bais = new ByteArrayInputStream(yourjsonString.getBytes(StandardCharsets.UTF_8));
metadataOptionJsonProprties.put("jcr:data", bais);
LOG.debug(String.format("%s : %s", "Options Json ", metadataOptionJson.getPath()));
resolver.commit();

2 comments: