New Start
New Start

Reputation: 1421

Recursively print the keys and values of a Hashtable, that includes HashTables and ArrayLists

This might be stupid/overly complicated/near impossible, but...

I have a JSON file. I used a C# class (http://bit.ly/1bl73Ji) to parse the file into a HashTable.

So, I now have a HashTable. This HashTable has Keys and Values. But, some of these Values are ArrayLists or HashTables. Sometimes these ArrayLists contain HashTables, sometimes the HashTables contain Hashtables, and so on and so forth...

I'm basically just trying to print these keys and values into a file, just using simple indentation to differentiate, e.g.

dateLastActivity
    2013-07-01T13:50:51.746Z
members
    memberType
        normal
    avatarHash
        5f9a6a60b6e669e81ed3a886ae
    confirmed
        True
    status
        active
    url
        www.awebsite.com
    id
        4fcde962a1b057c46607c1
    initials
        AP
    username
        ap
    fullName
        A Person
    bio
        Software developer

I need to recursivley go through the Hashtable, checking if the value is an ArrayList or HashTable, and keep checking and checking until it's just a string value. I've had a crack at it but I just can't seem to wrap my head around the recursive-ness.

Can anybody help? Even if somebody can think of a better way or if I should just abandon hope, I'd like to hear it!

Thanks in advance!

Upvotes: 0

Views: 561

Answers (2)

konkked
konkked

Reputation: 3231

There is a Library for that

I honestly would just use Json.NET, that is what I use to deal with my Json in pretty much all of my projects, it is kept up to date and works extremely well.

It also is good if you want a file format that is easy to humanread, to serialize (serialize means to transform into a data representation) your data and have a human edit it later on. It comes with the ability to Serialize pretty much most object out-of-the-box.

For most objects all you have to do is this statement to serialize your data into a string.


 string s = JsonConverter.Serialize(theObject);
 //assume you have a write file method
 WriteFile(filename, s);

that's it to serialize in most cases and to deserialize is just as easy


string content = ReadFile(filename);
MyObject obj = JsonConverter.Deserialize(content);

the library also includes support for anonymous objects, allows you to specify how your object is parsed with attributes, and a lot of other cool features, while also being faster then the built in .NET version

Upvotes: 1

mouse
mouse

Reputation: 11

Pseudo-code answer:

main(){
recurse(0, myHashTable)
}

recurse(int level, Structure tableOrArray){
     for element x in tableOrArray{
          if(x is a string) print (level)*indent + x;
          if(x is not a string) recurse(level + 1, x)
     }
}

Upvotes: 1

Related Questions