Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I navigate any JSON tree in c#?

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)

like image 476
juan Avatar asked Feb 09 '11 15:02

juan


1 Answers

Read this article:

  • http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx

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:

  • http://json.codeplex.com/

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

like image 117
Matías Fidemraizer Avatar answered Sep 19 '22 18:09

Matías Fidemraizer