2

I have this bit of code:

JSONArray data = object.getJSONArray("Test");

for (int i = 0; i < data.length(); i++)
{
    JSONObject dataObject = data.getJSONObject(i);
    etc ...

I don't know before run time what I will have in dataObject though. Is it possible to loop through the keys somehow?

I thought this might work, as I saw it mentioned in another Stackoverflow article:

for (String key : dataObject.keys())

But I get an error saying "Can only iterate over an array or an instance of java.lang.Iterable"

Does anyone know how it can be done?

4
  • Can you post your Json structure? Commented Oct 28, 2013 at 8:29
  • post your JSON structure Commented Oct 28, 2013 at 8:30
  • It will be determined dynamically, but it will look something like this: {"Test":[{"CouldBeAnything":"CBA_Value","CouldBeSomethingElse":"CBSE_Value", ... }, {"CouldBeAnything2":"CBA2_Value","CouldBeSomethingElse2":"CBSE2_Value", ... }]} Commented Oct 28, 2013 at 8:32
  • Check this Commented Oct 28, 2013 at 10:29

4 Answers 4

4

To Retrieving the keys of your object this might work :

Iterator<?> iterator = object.keys();
while (iterator.hasNext()) {
   String key = (String)iterator.next();
   //do what you want with the key.                 
}  
Sign up to request clarification or add additional context in comments.

Comments

0
JSONArray names()
Returns an array containing the string names in this object.

http://developer.android.com/reference/org/json/JSONObject.html

Comments

0

I hope this will help

Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;

Refer below link

http://json.org/java/

http://www.tutorialspoint.com/json/json_java_example.htm

Comments

0

i guess

Iterator keys = json.keys();

this will give you the keys of your json object as java iterator

How can I iterate JSONObject to get individual items

This will give you an idea to get the keys and values in iterative manner and helps you to implement for your need

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.