7

I need to navigate a Json structure as I would navigate an XML using XmlDocument.

The structure is not known, and I need to iterate over the nodes to parse some data.

Is this possible?
I know I can use JavaScriptSerializer to deserialize it into a known type, but this is not the case as I can receive any valid json.

I'm using .NET 3.5 (SP1) and cannot upgrade to 4.0 at the moment.
I upgraded to .NET 4.0 to use dynamic types (which is awesomeness made code)

juan
  • 80,295
  • 52
  • 162
  • 195
  • possible duplicate of [Parse JSON in C#](http://stackoverflow.com/questions/1212344/parse-json-in-c) – Jason Feb 09 '11 at 15:04
  • 3
    @Jason, this is not a duplicate, I specifically state that I don't know the structure so I cannot deserilize it to a known type. – juan Feb 09 '11 at 15:07
  • Right; the linked question is centered around JSON.NET, not JavaScriptSerializer. The former allows you to walk and inspect the resulting structure, the latter is for static types. – Jason Feb 10 '11 at 03:20

1 Answers1

3

Read this article:

It explains you a way of parsing JSON to a dynamic object which has a dictionary inside.

So, iterating a dictionary would be nice with LINQ, wouldn't be?

--- OR IF YOU'RE IN .NET 3.5... --- ;)

Why don't you implement an extension method like "ToDictionary"?

You can receive JSON text, later parse with a regular expression and split properties and values into a dictionary, everything done with suggested extension method.

A sample of how it would work that:

IDictionary<string, object> deserializedJson = jsonText.ToDictionary();

Fits your needs?

--- EVEN YET ANOTHER TRY (now you've more options)! ---

Check this open source project on CodePlex:

It has LINQ-to-JSON so you can read and write JSON.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • I forgot to say I'm using .NET 3.5 (Edit: But I could use that JavaScriptConverter thingy, I'm going to try it) – juan Feb 09 '11 at 15:08
  • I liked your first answer so much that I'm negotiating migrating the application to 4.0, I'll update with the results. – juan Feb 09 '11 at 15:28
  • Thanks. Well, I'll "un-strike" the first one, and I'll edit with a good "OR you can do that" ;) – Matías Fidemraizer Feb 09 '11 at 15:32
  • Can you update your answer with explanation from the first link? – maracuja-juice Feb 25 '22 at 15:39
  • @maracuja-juice It's been a very long time since this answer haha. I see all links are broken. Honestly, I don't remember what I was talking about. But I'll try it anyway... If I can't remember the thing, I'll proceed to delete my answer. – Matías Fidemraizer Mar 07 '22 at 07:40