tags:

views:

246

answers:

2

At present the structure of my code uses XmlDocument to load Xml and then SelectNodes to iterate through a list of repeating items. For each elements Im using XmlNode.SelectSingleNode to pick out field elements.

I now want to use JSON.NET to achieve the same results with documents delivered to me as Json. The answer can be something other than Json.net, as long as it's C# intergratable.

+1  A: 

Do you have an object hierarchy that you can map the the JSON? You could create an object tree (i.e. deserialize the JSON), and use LINQ's Where, SelectMany, etc.

Marc Gravell
Thanks for the response Marc. Specifically, Im using the twitter.com/status/mentions.json feed. I want to pass each "status" to an HTML Render without knowing (at buildtime) which fields it is using and allow it to pull fields with Json version of SelectSingleNode. A LINQ example would help alot :)
Dead account
Ah, right. It wouldn't allow you to use an arbitrary string, if that is what you mean. It would need coding per scenario.
Marc Gravell
+1  A: 

It hasn't been released yet but the latest version of the Json.NET source code has SelectToken. It uses a syntax similar to DataBinder.Eval to get JSON via a string expression:

JObject o = JObject.Parse("{'People':[{'Name':'Jeff'},{'Name':'Joe'}]}");

// get name token of first person and convert to a string
string name = (string)o.SelectToken("People[0].Name");

Or if you wanted to select multiple values:

JObject o = JObject.Parse("{'People':[{'Name':'Jeff','Roles':['Manager', 'Admin']}]}");

// get role array token of first person and convert to a list of strings
IList<string> names = (string)o.SelectToken("People[0].Roles").Select(t => (string)t).ToList();

You can get the latest source code here.

James Newton-King
Thanks James - I'll give that spin.
Dead account