Fetch data from Content Fragment and render in json script via HTML
Hi,
My requirement is to get the data from the content fragment multifield and then show those in a particular manner.
Here's the desired result :

In the backend I am getting the data from the Content Fragment and then splitting the array based on delimiter and subsequently creating a JSON array. Once the array is created, I've converted that to an array list. Here's the backend code :
private String[] openingHoursDays;
public String[] splitArray;
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
@PostConstruct
private void initModel() {
Resource fragmentResource = null;
if (fragmentResource != null) {
ContentFragment fragment = fragmentResource.adaptTo(ContentFragment.class);
if(fragment.getElement("openingHoursDays").getContent() !=null) {
openingHoursDays = fragment.getElement("openingHoursDays").getValue().getValue(String[].class);
}
}
}
public String[] getOpeningHoursDays( ) {
return openingHoursDays;
}
public ArrayList<String> getSplitArray() {
for (int i = 0; i < openingHoursDays.length; i++) {
splitArray = openingHoursDays[i].split("-"); //splitting the array based on delimiter (-)
try {
jsonObject.put("@type:", "OpeningHoursSpecification"); //creating the JSON objects
jsonObject.put("dayOfWeek", splitArray[i]); //creating the JSON objects at index 0
jsonObject.put("opens", splitArray[i+1]); //creating the JSON objects at index 1
jsonObject.put("closes", splitArray[i+2]); //creating the JSON objects at index 2
} catch (JSONException e) {
LOGGER.info("Unable to create JSON object");
}
jsonArray.put(jsonObject); //creating the JSON array from the JSON objects
}
ArrayList<String> listdata = new ArrayList<String>(); //For storing the data from JSON array in an array list
if (jsonArray != null) {
for (int m=0;m<jsonArray.length();m++){
try {
listdata.add(jsonArray.getString(m)); //Add JSON array data to the list
}
catch (JSONException e) {
LOGGER.info("Unable to create Array List");
}
}
}
return listdata;
}
Note : I have to display these data in the script (with the script type="application/ld+json").
Here's the content fragment for your reference :

I am unable to get hold of how to fetch the data in the HTML.
The error that I am getting is : org.apache.sling.scripting.sightly.render.ObjectModel Cannot access method splitArray on object sample.project.core.models.ContentInfoModel@57ef0ff9
Can someone please help me out with the code so as to be able to meet the requirements? Let me know if there any changes to the backend code and also how to fetch the values in the HTML (the values should be returned under the script with script type="application/ld+json")
Thanks!!

