blog games developers documentation portfolio gallery

Documentation:

Iterate through results

Let's say you imported some XML or JSON and want to access the members, but you're not completely sure how the hierarchy is set up.

If you did know the hierarchy you could do things like "importedHierarchy.GetHashtable(0).GetString("Author");

What we do know is that directly after import, the entire hierarchy is made up of ArrayLists, Hashtables and strings.

We start with:
Hashtable hierarchy - SimpleJsonImporter.Import(someJsonString);

We don't know the keys of the Hashtable, so we query the keys like this:

ICollection keyColl = hierarchy.Keys;
foreach(string key in keyColl) {
// do something
}

We don't know the type of the key values, but we can make sure they are always of the type ArrayList. (The boolean makes sure that if the value is a Hashtable or something else, it is always wrapped in an ArrayList)

ArrayList level1 = hierarchy.GetArrayList(key, true);
Debug.Log(key + " contains "+level1.Count+" elements");

So now we can loop through the 1st level, by using strong types

for(int i=0;i<level1.Count;i++) {
ArrayList arrayContents = level1.GetArrayList(i);
if(arrayContents != null) {
Debug.Log(Found an arraylist at index "+i);
continue;
}
Hashtable hashContents = level1.GetHashtable(i);
if(hashContents != null) {
Debug.Log(Found a hashtable at index "+i);
continue;
}
string stringContents = level1.GetString(i);
if(stringContents != null) {
Debug.Log(Found a string at index "+i);
continue;
}
}

or by using the generic object type

for(int i=0;i<level1.Count;i++) {
object contents = level1[i];
if(contents.GetType() == typeof(ArrayList)) {
Debug.Log(Found an arraylist at index "+i);
} else if(contents.GetType() == typeof(Hashtable)) {
Debug.Log(Found a hashtable at index "+i);
} else if(contents.GetType() == typeof(string)) {
Debug.Log(Found a string at index "+i);
}
}



The whole example:

Hashtable hierarchy - SimpleJsonImporter.Import(someJsonString);
ICollection keyColl = hierarchy.Keys;
foreach(string key in keyColl) {
ArrayList level1 = hierarchy.GetArrayList(key, true);
Debug.Log(key + " contains "+level1.Count+" elements");
for(int i=0;i<level1.Count;i++) {
ArrayList arrayContents = level1.GetArrayList(i);
if(arrayContents != null) {
Debug.Log(Found an arraylist at index "+i);
continue;
}
Hashtable hashContents = level1.GetHashtable(i);
if(hashContents != null) {
Debug.Log(Found a hashtable at index "+i);
continue;
}
string stringContents = level1.GetString(i);
if(stringContents != null) {
Debug.Log(Found a string at index "+i);
continue;
}
}
}







follow us