Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.
SOLVED

unable to access JSONObject in sightly html file

Avatar

Level 3

Hi,

I am trying to access JSONObject  in sightly html,but the data is not displayed.

Below is the sightly java file,where "result" variable is holding JSON string.

public class TestSightly extends WCMUse {

   public String result;
   public JSONObject jsonObject;   
    
    @Override
    public void activate() throws Exception {
        TestLocation testLocation = new TestLocation();
        result = testLocation.testMessage();
        jsonObject = new JSONObject(result);
        
    }

     public String getResult(){
        return result;
    }
    
    public JSONObject getJsonObject(){
        return jsonObject
    }
       
}

HTML File:

<div data-sly-include="/libs/wcm/core/components/init/init.jsp"></div>

<div data-sly-use.model="${'com.test.core.models.TestSightly'}">
 <div>${model.result}</div>
 <div>${model.jsonObject}</div>

</div>

 

With the above "model.result" is displaying the string data(json formatted data),but "model.jsonObject" is displaying nothing.

 

Thanks & Regards

swati

1 Accepted Solution

Avatar

Correct answer by
Level 3

Issue fixed.Found alternate way.

Instead of using org.apache.sling.commons.json.JSONObject API, I changed to GSON api and converted json to javabean object and then accessing in sightly file.

But using JSONObject in sightly is still not possible.

swati

View solution in original post

17 Replies

Avatar

Level 9

Are you seeing any error in error.log when this expression is eveluating??

-Kishore

Avatar

Level 9

Just validate result string whether it is correct json or not. And, if there is any invalid json exception, you will have some error message in error.log

Jitendra

Avatar

Level 3

No errors in the error log and even json is correct as I am getting the json of jcr node with infinity.json,so I dont think there will be errors in the json.

I am able to parse the individual keys of json string in sightly java file and print the values like below,

String posts = json.getJSONObject("testkey1");
 String  test = posts.getString("testkey2");

But unable to access direct JSONObject.

I am trying to avoid parsing keys and values of json in java file (because if I do it ,I have to hardcode keys of json in java file)

Avatar

Level 9

I suspect that result string is not a jsonObject. it is a jsonArray. Would you mind returning jsonArray than JSONObject?.

Jitendra

Avatar

Level 3

result is string and it is in json format.Once I get it the result, I am converting it into JSONObject.

As you suggested, I changed it to JSONArray but no luck.

JSONArray jsonArray = new JSONArray(result);

Avatar

Level 9

In which format this "result" string is constructed and passed to JSONObject??

Below is the javadoc details of JSONObject(String).Please refer.

JSONObject

public JSONObject(String string) throws JSONException
Construct a JSONObject from a string. This is the most commonly used JSONObject constructor.

string - A string beginning with { (left brace) and ending with } (right brace).

Throws:

JSONException - If there is a syntax error in the source string.

Avatar

Level 3

I am using JSONObject with string as parameter to construct JSONObject.As I mentioned before I am getting the json string from infinity.json(from jcr nodes). Below is the sample json string which I am converting to JSONObject,

 

{  
   "jcr:primaryType":"nt:unstructured",
   "testkey1":{  
      "jcr:primaryType":"nt:unstructured",
      "test1":"al",
      "test2":"Alabama",
      "test3":"US"
      
      
   },
   "testkey2":{  
      "jcr:primaryType":"nt:unstructured"
   }
}
 

Thanks,

Swati

Avatar

Level 9

Swathi,

I think the issue is not with the Sightly POJO file. Do you mind testing same thing with JSP?.  It is just a guess that something strange happening because of Sightly.

Jitendra

Avatar

Level 3

I already tried with jsp, it is working fine.When I tried to convert that jsp to sightly html file,I faced this issue.

Avatar

Level 9

Yes. I had the same feeling. Try using context="unsafe" while rendering json object. Just try that.

for instance 

${jsonObject @ context='unsafe'}

Jitendra

Avatar

Correct answer by
Level 3

Issue fixed.Found alternate way.

Instead of using org.apache.sling.commons.json.JSONObject API, I changed to GSON api and converted json to javabean object and then accessing in sightly file.

But using JSONObject in sightly is still not possible.

swati

Avatar

Level 9

Thanks for sharing it.

Helpful!!!

Avatar

Community Advisor

Thanks for sharing your solution 

Avatar

Level 2

I got the same issue, I spent one day to understand why I'm unable to get the value of a JsonObject in sightly (only key) if the JsonObject come a java code with org.apache.sling.commons.json.JSONObject;

At the end I end up with another solution than the use of Gson api.

I used a JS conversion between java and sightly. I gave my Java JsonObject to a Javascript method JSON.parse()

something like:

html

<sly data-sly-use.greatdeals="GreatDeals" />

    <sly data-sly-use.greatdealsJS="${'greatdeals.js' @ jsonString=greatdeals.jsonGreatDeals}" />

<sly data-sly-list.deal="${greatdealsJS}">

    <div>${deal} : ${greatdealsJS[deal]}</div>

</sly>

greatdeal.js:

use(function () {

    return JSON.parse(this.jsonString);

});

GreatDeals

public JSONObject getJsonGreatDeals() {

        JSONObject jsonObject = null;

        try {

            jsonObject = new JSONObject();

            jsonObject.put("deal1", "test1");

            jsonObject.put("deal2", "test2");

            jsonObject.put("deal3", "test3");

        } catch (Exception e) {

            LOGGER.error("Could not create JSON", e);

        }

        return jsonObject;

    }

it's not beautiful but it works.

Avatar

Level 10

that is the nice thing about AEM - you are not bound to a specific API. Its essentially a JAVA platform, so you can use a specific Java API that will solve your business requirements.

A rule is the Java API must be in a OSGi bundle and in an active state so other bundles can use that API.

We have an article that shows use of the GSON API in a Java backend:

Scott's Digital Community: Creating an AEM HTML Template Language Component that displays data from ...

Avatar

Level 2

I agree with you and it's one of many reason I do JAVA and not .Net, because you can use and mix different API.

I just start with sightly instead of doing everything with a JSP, and was a litlle upset to not understand why an API from Google works better than an API from Apache in AEM