3

i have a JSON object which looks something like this:

cb = {"content":[{"name":"abc"}{"name":"bcd"}{"name":"xyz"}...]}

and i have imported the JSON library as:

import org.json.JSONObject;

Now i want to use a for loop to retrieve the values of name in each of the sub objects...

for(int x = 10; x < numberOfSubElemtnts; x = x+1) {
     //print out the name values
  }

Output should be:

abc

bcd

xyz

How should I evaluate the length of the array and print out the name values?

5
  • 3
    Look into the library GSON its really amazing for this sort of thing. Commented Mar 1, 2016 at 0:20
  • sry i updated my question. I am using the JSON (JSONObject) library Commented Mar 1, 2016 at 0:23
  • 1
    then check out tutorialspoint.com/json/json_java_example.htm i think this is your libary and i think it answers your question Commented Mar 1, 2016 at 0:25
  • sry not helping much...can you provide the example snippet of the for loop that needs to be constructed? Commented Mar 1, 2016 at 0:31
  • sure give me a few minutes Commented Mar 1, 2016 at 0:32

2 Answers 2

3

You can iterate the array like this:

    String content = "{\"content\":[{\"name\":\"abc\"},{\"name\":\"bcd\"},{\"name\":\"xyz\"}]}";
    JSONObject jsonObject = new JSONObject(content);
    JSONArray jsonArray = jsonObject.getJSONArray("content");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject object = jsonArray.getJSONObject(i);
        System.out.println(object.getString("name"));
    }
Sign up to request clarification or add additional context in comments.

Comments

1
JSONParser parser = new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try{
     Object obj = parser.parse(s);
     JSONArray array = (JSONArray)obj;
     for(int i=0;i<array.length();i++{
         System.out.println(array.get(i).getString("name");
      }
}catch(ParseException pe){
     System.out.println("position: " + pe.getPosition());
     System.out.println(pe);
  }

Also with this example youll have to change the format of your string to fit the one I have in mine

Comments

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.