[opencms-dev] JSON array from a list
Paoletti Corrado
c.paoletti at fineco.it
Fri Jan 14 09:05:26 CET 2022
Hi Tobias,
I have used your suggestions to simplified my code and study <cms:contentload, <cms:contentaccess ecc. that I never used before.
First of all:
${cms.requestContext.uri}
give the containerpage xml of the /newsroom/newsroom.html file (right button mouse > Advanced > Edit controlcode):
<?xml version="1.0" encoding="UTF-8"?>
<AlkaconContainerPages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="opencms://system/modules/org.opencms.ade.containerpage/schemas/container_page.xsd">
<AlkaconContainerPage language="en">
<Containers>
<Name><![CDATA[newsroom]]></Name>
<Type><![CDATA[page]]></Type>
<IsRootContainer>true</IsRootContainer>
<Elements>
<Uri>
<link type="STRONG">
<target><![CDATA[/sites/default/.content/newsroomList/newsroomList-00001.xml]]></target>
<uuid>ceb40485-6345-11ec-a62d-005056aa1567</uuid>
</link>
</Uri>
<Formatter>…
and not istance of resource type contained in /.content folder:
<?xml version="1.0" encoding="UTF-8"?>
<NewsroomLists xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="opencms://system/modules/*hiddenname*/schemas/newsroomList.xsd">
<NewsroomList language="en">
<Item>
<Id><![CDATA[how-to-invest-in-esg]]></Id>
<Category><![CDATA[INVESTING]]></Category>
<Date>1636710120000</Date> …
</Item>
<Item>
<Id><![CDATA[best-short-term-investments]]></Id>
<Category><![CDATA[BANKING]]></Category>
<Date>1638377040000</Date> …
</Item>
Using your suggestions the code become:
<cms:contentload collector="singleFile" param="${cms.requestContext.uri}" editable="false">
<cms:contentaccess var="content" />
<cms:contentload collector="singleFile" param="${content.valueList.Containers[0].value['Elements/Uri']}"> <%-- see https://stackoverflow.com/questions/31743481/xml-reading-out-nested-content --%>
<cms:contentaccess var="item" />
<c:set var="count" value="${fn:length(item.valueList.Item)}" />
<c:set var="index" value="0" />
[
<cms:contentloop element="Item">
<c:set var="index" value="${index+1}" />
{
"id": "<cms:contentshow element="Id" />",
"categoria": "<cms:contentshow element="Category" />"
}
<c:if test="${index < count}">,</c:if>
</cms:contentloop>
]
</cms:contentload>
</cms:contentload>
that is much better then first version!
Also, some days ago I tryed your solution concerned taglib http://www.atg.com/taglibs/json but I had Java error:
An error occurred.The absolute uri: http://www.atg.com/taglibs/json cannot be resolved in either web.xml or the jar files deployed with this application
I googled and found informations but I am not a Java programmer so I was going to see then in future...maybe ;-)
Thank you very very much.
Corrado
FinecoBank S.p.A. – Public
From: opencms-dev <opencms-dev-bounces at opencms.org> On Behalf Of Tobias Karrer via opencms-dev
Sent: mercoledì 12 gennaio 2022 19:34
To: Paoletti Corrado via opencms-dev <opencms-dev at opencms.org>
Cc: Tobias Karrer <kartobi at gmail.com>
Subject: Re: [opencms-dev] JSON array from a list
Hi!
why don't you use contentload tag?
Something like this (untested though):
<cms:contentload collector="singleFile" param="${cms.requestContext.uri}" editable="false">
<cms:contentaccess var="content"/>
<c:forEach items="${content.valueList.Item}" var="item" varStatus="status">
{
"id":"${item.value.Id}",
"categoria":"${item.value.Category}"
// ...
}<c:if test="${not status.last}">,</c:if>
</c:forEach>
</cms:contentload>
This should work as well:
<c:set var="uri" value="${cms.requestContext.uri}" />
<c:forEach items="${cms.vfs.xml[uri].valueList.Item}" var="item" varStatus="status">
...
</c:forEach>
BR, Tobias
Am 11.01.2022 um 08:49 schrieb Paoletti Corrado via opencms-dev:
FinecoBank S.p.A. - Internal Use Only
Hi,
finally I have obtain a JSON array without formatter's wrapper div: the JSON is written by template only when I publish file. I know the code is ugly but it works. I hope this may help someone.
<c:if test="${cms.isOnlineProject}">
<%
CmsJspActionElement cms = new CmsJspActionElement(pageContext, request, response);
CmsObject cmso = cms.getCmsObject();
Locale locale = cms.getRequestContext().getLocale();
String uri = cms.getRequest().getParameter("uri") == null ? cms.getRequestContext().getUri() : cms.getRequest().getParameter("uri");
CmsResource resourceViaPath = cmso.readResource(uri);
CmsJspContentAccessBean res = new CmsJspContentAccessBean(cmso, resourceViaPath);
// Get xml content file name... (e.g. /.content/newsroomList/newsroomList-00001.xml)
String xmlContentFileName = res.getRawContent().getStringValue(cmso, "Containers[1]/Elements[1]/Uri[1]", locale);
// ...then I read its content
CmsResource resourceViaPath2 = cmso.readResource(xmlContentFileName);
CmsJspContentAccessBean res2 = new CmsJspContentAccessBean(cmso, resourceViaPath2);
%>
[
<%for(int i=1; i<=res2.getRawContent().getValues("Item", locale).size(); i++) {%>
{
"id": "<%=res2.getRawContent().getValue("Item["+i+"]/Id[1]", locale).getStringValue(cmso)%>",
"categoria": "<%=res2.getRawContent().getValue("Item["+i+"]/Category[1]", locale).getStringValue(cmso)%>",
"tempoLettura": "<%=res2.getRawContent().getValue("Item["+i+"]/MinReading[1]", locale).getStringValue(cmso)%>",
"dataPubblicazione": "<%=res2.getRawContent().getValue("Item["+i+"]/Date[1]", locale).getStringValue(cmso)%>",
// ... and so on
}<%if(i<res2.getRawContent().getValues("Item", locale).size()) {%>,<%}%>
<%}%>
]
</c:if>
Corrado
From: opencms-dev <opencms-dev-bounces at opencms.org><mailto:opencms-dev-bounces at opencms.org> On Behalf Of ????????? ?????? ???????
Sent: venerdì 24 dicembre 2021 13:41
To: The OpenCms mailing list <opencms-dev at opencms.org><mailto:opencms-dev at opencms.org>
Subject: Re: [opencms-dev] JSON array from a list
We do not use formatter at all.
We made jsp file in public part of the site and pasted the code right in jsp file.
We iterate certain content type (NewsBlock) with Solr like this:
<c:set var='solrNewsQuery'>
{
"core" : "Solr Online",
"ignorequery" : true,
"ignoreReleaseDate" : false,
"ignoreExpirationDate" : false,
"queryparam" : ":",
"escapequerychars" : true,
"extrasolrparams" : "fq=parent-folders:\"${searchPath}\"&fq=type:NewsBlock&fq=category:Glavnaya&sort=Newsdate_prop desc",
"pagesize" : "10",
}
</c:set>
<cms:search configString="${solrNewsQuery}" var="search" addContentInfo="true" />
[
<c:forEach var="news" items="${search.searchResults}" varStatus="status">
.....
________________________________
От: opencms-dev <opencms-dev-bounces at opencms.org<mailto:opencms-dev-bounces at opencms.org>> от имени Paoletti Corrado <c.paoletti at fineco.it<mailto:c.paoletti at fineco.it>>
Отправлено: 24 декабря 2021 г. 15:32
Кому: The OpenCms mailing list
Тема: Re: [opencms-dev] JSON array from a list
FinecoBank S.p.A. - Internal Use Only
Hi,
finally when I publish the file I have JSON! Here the code in JSP formatter:
<%@page import="javax.servlet.http.HttpServletResponse,org.opencms.flex.CmsFlexController,org.apache.commons.lang3.StringEscapeUtils" %<mailto:%25 at page%20import=%22javax.servlet.http.HttpServletResponse,org.opencms.flex.CmsFlexController,org.apache.commons.lang3.StringEscapeUtils%22%20%25>>
<c:if test="${cms.isOnlineProject}">
<%
HttpServletResponse topLevelResponse = CmsFlexController.getController(request).getTopResponse();
topLevelResponse.setHeader("Content-Type","application/json;charset=UTF-8");
topLevelResponse.setHeader("Access-Control-Allow-Origin", "*");
%>
[
<c:forEach var="elem" items="${content.valueList.Item}" varStatus="status">
<c:set var="Id">${elem.value.Id}</c:set>
<c:set var="Category">${elem.value.Category}</c:set>
{
"id" : "<%=StringEscapeUtils.escapeEcmaScript(pageContext.getAttribute("Id").toString())%>",
}${status.last ? "" : ","}
</c:forEach>
]
</c:if>
The last little thing before perfection... My JSP template has:
<cms:container name="newsroom" type="page" editableby="ROLE.WORKPLACE_USER" maxElements="200">
<h4>Drag here newsroom element</h4>
</cms:container>
so JSON is:
<div id="newsroom" >
[
{
"name" : "giulio",
"surname": "cesare"
},
{
"name" : "dante",
"surname", "alighieri"
}
]
</div>
How can I remove the wrapping div?
Many thanks for your help!
Corrado
From: opencms-dev <opencms-dev-bounces at opencms.org<mailto:opencms-dev-bounces at opencms.org>> On Behalf Of ????????? ?????? ???????
Sent: giovedì 23 dicembre 2021 13:24
To: The OpenCms mailing list <opencms-dev at opencms.org<mailto:opencms-dev at opencms.org>>
Subject: Re: [opencms-dev] JSON array from a list
We made jsp file and use following code to return news items in json:
<%@page buffer="none" session="false" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="javax.servlet.http.HttpServletResponse,org.opencms.flex.CmsFlexController,org.apache.commons.lang3.StringEscapeUtils" %<mailto:%25 at page%20import=%22javax.servlet.http.HttpServletResponse,org.opencms.flex.CmsFlexController,org.apache.commons.lang3.StringEscapeUtils%22%20%25>>
<%
HttpServletResponse topLevelResponse = CmsFlexController.getController(request).getTopResponse();
topLevelResponse.setHeader("Content-Type","application/json;charset=UTF-8");
topLevelResponse.setHeader("Access-Control-Allow-Origin", "*");
%>
<c:set var="searchPath">${cms.requestContext.siteRoot}/</c:set>
<c:set var='solrNewsQuery'>
{
"core" : "Solr Online",
"ignorequery" : true,
"ignoreReleaseDate" : false,
"ignoreExpirationDate" : false,
"queryparam" : ":",
"escapequerychars" : true,
"extrasolrparams" : "fq=parent-folders:\"${searchPath}\"&fq=type:NewsBlock&fq=category:Glavnaya&sort=Newsdate_prop desc",
"pagesize" : "10",
}
</c:set>
<cms:search configString="${solrNewsQuery}" var="search" addContentInfo="true" />
[
<c:forEach var="news" items="${search.searchResults}" varStatus="status">
<c:set var="convertId">${news.xmlContent.id}</c:set>
<c:set var="convertTitle">${news.xmlContent.value.Title}</c:set>
<c:set var="convertDescription">${news.xmlContent.value.ShortDescription}</c:set>
<c:set var="convertFullDescription">${news.xmlContent.value.FullDescription}</c:set>
<c:set var="convertPrewImg">https://www.mysite.ru<cms:link>${news.xmlContent.value.ImagePreview}</cms:link></c:set<https://www.mysite.ru%3ccms:link%3e$%7bnews.xmlContent.value.ImagePreview%7d%3c/cms:link%3e%3c/c:set>>
<c:set var="convertUrl">https://www.mysite.ru<cms:link>${news.xmlContent.filename}</cms:link></c:set<https://www.mysite.ru%3ccms:link%3e$%7bnews.xmlContent.filename%7d%3c/cms:link%3e%3c/c:set>>
<fmt:setLocale value="ru-RU"/>
<fmt:timeZone value="GMT+3:00">
<fmt:formatDate type = "both" dateStyle = "long" timeStyle = "long" value = "${cms:convertDate(news.xmlContent.value.Date)}" var="fullDate"/>
<c:set var="formatedDateArray" value='${fn:split(fullDate, " ")}' />
</fmt:timeZone>
<c:set var="convertDate">${formatedDateArray[0]} ${formatedDateArray[1]} ${formatedDateArray[2]}</c:set>
{
"id" : "<%=StringEscapeUtils.escapeEcmaScript(pageContext.getAttribute("convertId").toString())%>",
"date" : "<%=StringEscapeUtils.escapeEcmaScript(pageContext.getAttribute("convertDate").toString())%>",
"title": "<%=StringEscapeUtils.escapeEcmaScript(pageContext.getAttribute("convertTitle").toString())%>",
"short_description": "<%=StringEscapeUtils.escapeEcmaScript(pageContext.getAttribute("convertDescription").toString())%>",
"full_description": "<%=StringEscapeUtils.escapeEcmaScript(pageContext.getAttribute("convertFullDescription").toString().replaceAll("src=\"","src=\"https://www.mysite.ru").replaceAll("\\<iframe[^>]*><file://%3ciframe[%5e%3e]*%3e>","").replaceAll("\\<a[^>]*><file://%3ca[%5e%3e]*%3e>",""))%>",
"url": "<%=StringEscapeUtils.escapeEcmaScript(pageContext.getAttribute("convertUrl").toString())%>",
"img": "<%=StringEscapeUtils.escapeEcmaScript(pageContext.getAttribute("convertPrewImg").toString())%>"
}${status.last ? "" : ","}
</c:forEach>
]
________________________________
От: opencms-dev <opencms-dev-bounces at opencms.org<mailto:opencms-dev-bounces at opencms.org>> от имени Paoletti Corrado <c.paoletti at fineco.it<mailto:c.paoletti at fineco.it>>
Отправлено: 23 декабря 2021 г. 15:15
Кому: opencms-dev at opencms.org<mailto:opencms-dev at opencms.org>
Тема: [opencms-dev] JSON array from a list
FinecoBank S.p.A. - Internal Use Only
Hi,
my target is to generate a JSON response from a list of users.
With one user <cms:jsonpart generates a correct JSON but when I use it inside a <c:forEach I obtain only the last user so I deduce that <cms:jsonpart is not sufficient.
Searching examples and documentation I find that I could use a combination of JSONArray and JSONObject and these objects are defined in cms taglibrary (https://documentation.opencms.org/javadoc/tld/cms/jsonarray.html)
So, I have write <cms:jsonarray but I have:
No tag "jsonarray" defined in tag library imported with prefix "cms"
Someone could suggest me the right way to follow to have a JSON array like this:
[
{"name":"giulio", "surname":"cesare"},
{"name":"dante", "surname":"alighieri"},
]
Another approach is to use Java (I am not Java programmer) so I have wrote:
<%@page import="org.opencms.json.JSONException, org.opencms.json.JSONArray, org.opencms.json.JSONObject"%<mailto:%25 at page%20import=%22org.opencms.json.JSONException,%20org.opencms.json.JSONArray,%20org.opencms.json.JSONObject%22%25>>
<%
JSONObject user = new JSONObject();
try {
user.put("name", "giulio");
user.put("surname", "cesare");
} catch (JSONException e) {
}
JSONArray userList = new JSONArray();
userList.put(user);
System.out.println( userList );
%>
but nothing happens.
Kind regards and Happy Christmas.
Corrado
_______________________________________________
This mail is sent to you from the opencms-dev mailing list
To change your list options, or to unsubscribe from the list, please visit
https://lists.opencms.org/mailman/listinfo/opencms-dev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.opencms.org/pipermail/opencms-dev/attachments/20220114/ff1253e9/attachment.htm>
More information about the opencms-dev
mailing list