hnvasa
hnvasa

Reputation: 860

Java - retrieving JSON object values

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?

Upvotes: 3

Views: 1264

Answers (2)

Arachnid Hivemind
Arachnid Hivemind

Reputation: 504

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

Upvotes: 1

Diego Farias
Diego Farias

Reputation: 66

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

Upvotes: 3

Related Questions