tags:

views:

3198

answers:

2

I’m trying to work with some json formatted data in C#, but, I’m having some problems determining the proper way to approach the problem. My issue is that the json formatted data will be in an unknown format (I know that sounds odd … please read on). Basically, the json formatted data will be some collection of name/value pairs where the values may or may not be arrays of nested name/value pairs. To make things more fun, the nesting of the name/value pair arrays can continue on ad infinitum.

For example: I might have some data that looks like…

{ “1” {
    “1.1”: { “1.1.1”: “value1”, “1.1.2”: “value2”, “1.1.3”: “value3” },
    “1.2”: “value4”,
    “1.3”: { “1.3.1”:
      { “1.3.1.1”: “value5”, “1.3.1.2”: “value6” },
       “1.3.1.2”: “value7”,
      “1.3.1.3”: “value8”,
     }
    } 
}

Unfortunately, I don’t know how much nesting is going to occur and technically I don’t know what names/value pairs will be present in any given message.

Is there any supported mechanism in C# that would enable me to easily parse this into a nested set of hastables?

I’d like to do something along the lines of (note this code is not 100% syntactically correct and would better be done via recursion … but it get’s the idea across).

Hashtable ht = [deserialize data method](jsonformattedstring);
foreach (Hashtable nested in ht)
{
    If (nested.count > 1)
        {
     Foreach (hashtable next in nested)
     …
        }
}
+2  A: 

In .NET, you have the JsonArray, which allows you to load up and parse the JSON data. It creates an array of JsonValue and it is completely nested based on the JSON data it parses.

If you specifically need Hashtable, you could translate the data from JsonArray, though Hastable is all but deprecated in favor of Dictionary.

Josh Holmes has a pretty good "getting started" post about JSON in .NET: http://www.joshholmes.com/blog/2009/01/20/PlayingWithJSON.aspx

Brian Genisio
+2  A: 

I didn't like the .Net Json parsing...it does some strange things occasionally. I've switched to Json.NET, an open source library. It has a nice JObject object that will do what you need.

jvenema
JSON.NET worked quite well (after spending a lot of time working through its intricacies). My only criticism would be that the JObject, JValue, and other “lower level” objects are not well documented. Thanks for pointing me in the right direction.