1

I have a JAVA for loop which prints the out put as shown below.

inside for loop::{"state":"tess","path":"/content/projectpath/en/men"} inside for loop::{"state":"hello","path":"/content/projectpath/en/women"}

Any my code snippet is as shown below.

for (Value val : values) {
                    //jsonobj = new JSONObject(val.getString());
                    out.println("inside for loop::" + val.getString());
                  // JSONArray jsonarr = val.getString();
               }// out.println("::"+jsonobj.toString());

How to get a JSON Array after the for loop which should have the values {"state":"tess","path":"/content/projectpath/en/men"} and {"state":"hello","path":"/content/projectpath/en/women"}

3
  • Your JSON data should be parsed as a JSONObject, not a JSONArray because it's object data, not an array. Commented Feb 20, 2017 at 21:35
  • @TedHopp its a multi valued string array, which i will get from the JCR, which is required to formulate as JSON ARRAY Commented Feb 20, 2017 at 21:37
  • Okay. I reopened the question, as I thought it was about parsing. I see that @Kumaresan posted a workable solution. Commented Feb 20, 2017 at 21:43

1 Answer 1

3

create a JSONArray like this. insert your looping object on list. Finally you will get an array please try it.

JSONArray list = new JSONArray();
list.add(val);
Sign up to request clarification or add additional context in comments.

5 Comments

it gives me the The method add(String) is undefined for the type JSONArray error with JSONArray list = new JSONArray(); list.add(val.getString()); code
JSONParser parser = new JSONParser(); String response = "{"state":"tess","path":"/content/projectpath/en/men"}"; JSONObject jsonObj = (JSONObject) parser.parse(response);
then add your object on list. refer thid link : stackoverflow.com/questions/5015844/parsing-json-object-in-java
Thank you, is there any possibility with import org.apache.sling.commons.json.JSONObject; import org.apache.sling.commons.json.JSONArray APIs for the same logic.
When you're using Apache Sling's version of JSONArray, instead of add(), the method is called put().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.