I have a simple key/value list in JSON being sent back to ASP.NET via POST. Example:
{ "key1": "value1", "key2": "value2"}
I AM NOT TRYING TO DESERIALIZE INTO STRONGLY-TYPED .NET OBJECTS
I simply need a plain old Dictionary(Of String, String), or some equivalent (hash table, Dictionary(Of String, Object), old-school StringDictionary--hell, a 2-D array of strings would work for me.
I can use anything available in ASP.NET 3.5, as well as the popular Json.NET (which I'm already using for serialization to the client).
Apparently neither of these JSON libraries have this forehead-slapping obvious capability out of the box--they are totally focused on reflection-based deserialization via strong contracts.
Any ideas?
Limitations:
- I don't want to implement my own JSON parser
- Can't use ASP.NET 4.0 yet
- Would prefer to stay away from the older, deprecated ASP.NET class for JSON
I would suggest using
System.Runtime.Serialization.Json
that is part of .NET 4.5.Then use it like this:
I added a check for null values in the JSON to the other answer
I had same problem so I wrote this my self. This solution is differentiated from other answers because it can deserialize in to multiple levels.
Just send json string in to deserializeToDictionary function it will return non strongly-typed
Dictionary<string, object>
object.Ex: This will return
Dictionary<string, object>
object of a Facebook JSON response.Note: hometown further deserialize into a
Dictionary<string, object>
object.I've added upon the code submitted by jSnake04 and Dasun herein. I've added code to create lists of objects from
JArray
instances. It has two-way recursion but as it is functioning on a fixed, finite tree model, there is no risk of stack overflow unless the data is massive.Annoyingly enough, if you want to use the default model binders, it looks like you will have to use numerical index values like a form POST.
See the following excerpt from this article http://msdn.microsoft.com/en-us/magazine/hh781022.aspx:
I just needed to parse a nested dictionary, like
where
JsonConvert.DeserializeObject
doesn't help. I found the following approach:The
SelectToken
lets you dig down to the desired field. You can even specify a path like"x.y.z"
to step further down into the JSON object.My approach directly deserializes to IDictionary, without JObject or ExpandObject in between. The code uses converter, which is basically copied from ExpandoObjectConverter class found in JSON.NET sourcecode, but using IDictionary instead of ExpandoObject.
Usage:
Code: