AEM code snippets : How to get multifield values into json format using Gson

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

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 

In the sightly template add below code

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

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