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?

b85411
  • 9,420
  • 15
  • 65
  • 119
  • Can you post your Json structure? – Amit Gupta Oct 28 '13 at 08:29
  • post your JSON structure – Shruti Oct 28 '13 at 08: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", ... }]} – b85411 Oct 28 '13 at 08:32
  • Check [this](http://stackoverflow.com/questions/19398204/how-to-parse-a-json-array-with-the-same-structure-but-different-names/19398566#19398566) – Jhanvi Oct 28 '13 at 10:29

4 Answers4

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.                 
}  
KunalK
  • 1,904
  • 4
  • 22
  • 40
0
JSONArray names()
Returns an array containing the string names in this object.

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

baltov
  • 194
  • 5
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

Hariharan
  • 3,191
  • 4
  • 19
  • 31
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

Community
  • 1
  • 1
sam
  • 2,426
  • 2
  • 20
  • 29