Here, I am using Gson to convert multifield values into JSON format, the first thing which we need to do is first load the Gson maven dependency

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

I am using below code to read the multifield control child nodes, once the list is populated with Link bean objects then using gson.toJson() method convert entire list into JSON 

package com.aem.toolkit.core.models;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Optional;
import org.apache.sling.api.resource.Resource;
import com.adobe.cq.sightly.WCMUsePojo;
import com.google.gson.Gson;
public class ListCollectionGenerics extends WCMUsePojo {
	public java.util.List<Link> links;
	public java.util.List<Link> getLinks() {
		Resource childResource = getResource().getChild("items");
		if (childResource != null) {
			Iterator<Resource> linkResources = childResource.listChildren();
			linkResources.forEachRemaining(res -> populateModel(res).ifPresent(links::add));
		}
		return links;
	}
	public Optional<Link> populateModel(Resource resource) {
		links = new ArrayList<Link>();
		Link link = new Link();
		link.setTitle((String) resource.getValueMap().get("linkText"));
		link.setUrl((String) resource.getValueMap().get("linkUrl"));
		return Optional.of(link);
	}
        public String getLinksAsJsonFormat()
        {
           Gson gson = new Gson();
           return gson.toJson(links);
        }
	@Override
	public void activate() throws Exception {
	}
}

In the sightly template add below code

<sly data-sly-use.listUse="com.aem.toolkit.core.models.ListCollectionGenerics">
${listUse.linksAsJsonFormat}
</sly>

The output is something like below
json-format

Serializing certain properties

If you want to serialize only certain properties then you can use Gson based @expose option something like below, the below code will serialize the only linkUrl properly and it will not serialize linkText property

package com.aem.toolkit.core.models;
import com.google.gson.annotations.Expose;
public class Link {
	private String linkText;
	@Expose(serialize = true)
	private String linkUrl;
	public void setTitle(String linkText) {
		this.linkText = linkText;
	}
	public void setUrl(String linkUrl) {
		this.linkUrl = linkUrl;
	}
	public String getTitle() {
		return linkText;
	}
	public String getUrl() {
		return linkUrl;
	}
}

In order to work @expose annotation’s properly, you must create Gson instance by using the GsonBuilder class, check below code

      GsonBuilder builder = new GsonBuilder();
		builder.excludeFieldsWithoutExposeAnnotation();
		Gson gson = builder.create();
		return gson.toJson(links);

 

By coderss

Leave a Reply

Your email address will not be published. Required fields are marked *