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"}

krish
  • 469
  • 1
  • 15
  • 34
  • Your JSON data should be parsed as a JSONObject, not a JSONArray because it's object data, not an array. – Ted Hopp Feb 20 '17 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 – krish Feb 20 '17 at 21:37
  • Okay. I reopened the question, as I thought it was about parsing. I see that @Kumaresan posted a workable solution. – Ted Hopp Feb 20 '17 at 21:43

1 Answers1

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);
Kumaresan Perumal
  • 1,926
  • 2
  • 29
  • 35
  • 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 – krish Feb 20 '17 at 21:50
  • JSONParser parser = new JSONParser(); String response = "{"state":"tess","path":"/content/projectpath/en/men"}"; JSONObject jsonObj = (JSONObject) parser.parse(response); – Kumaresan Perumal Feb 20 '17 at 21:55
  • then add your object on list. refer thid link : http://stackoverflow.com/questions/5015844/parsing-json-object-in-java – Kumaresan Perumal Feb 20 '17 at 21:55
  • 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. – krish Feb 20 '17 at 22:42
  • 1
    When you're using Apache Sling's version of `JSONArray`, instead of `add()`, the method is called `put()`. – Ted Hopp Feb 21 '17 at 06:35