views:

43

answers:

3

I'd like to be able to parse a string of JSON representing an object into a property bag (like a Dictionary) which I can use in C#.

Given this string:

{ "id":1, "name":"some name", "some parameter":2 }

I want to end up with a Dictionary which contains "id", "name", and "some parameter" as keys and 1, "some name", and 2 as values respectively.

I don't want to parse the JSON string myself - maybe there's a library (preferably in the .net framework) that I can lean on to do the parsing for me to give access to the key/values in the JSON object. Or is there a deserializer available which I can explicitly tell which .net type to target?

In my scenario I'll only ever have one root "object" (it won't start with an array).

Thanks.

+2  A: 
var json = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue };
var dict = (IDictionary<string, object>)json.DeserializeObject(yourString);
John Fisher
Works perfectly - thank you.
Daniel James Bryars
A: 

JavaScriptSerializer should do what you need.

Also, Json.NET if you don't mind going 3rd party.

Robert Greiner
A: 

Have you looked at the DataContractJsonSerializer and JavaScriptSerializer to see if either of those meet your needs?

If not, you could also try JSON.NET

Justin Niessner
I'd seen the DataContractJsonSerializer, but hadn't seen the JavaScriptSerializer (as used in Fisher's answer.) Thanks.
Daniel James Bryars