b85411
b85411

Reputation: 10000

How to parse unknown JSON structure in Java

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?

Upvotes: 2

Views: 8602

Answers (4)

KunalK
KunalK

Reputation: 1904

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

Upvotes: 4

sam
sam

Reputation: 2486

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

Upvotes: 0

Hariharan
Hariharan

Reputation: 3263

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

Upvotes: 0

baltov
baltov

Reputation: 194

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

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

Upvotes: 0

Related Questions