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
For those searching the internet and stumbling upon this post, I wrote a blog post on how to use the JavaScriptSerializer class.
Read more... http://procbits.com/2011/04/21/quick-json-serializationdeserialization-in-c/
Here is an example:
I had the 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.Old code
Ex: This will return
Dictionary<string, object>
object of a Facebook JSON response.Test
Update
My old answer works great if there is no array on JSON string. This one further deserialize in to a
List<object>
if an element is an array.Just send a JSON string in to deserializeToDictionaryOrList function it will return non strongly-typed
Dictionary<string, object>
object orList<object>
.Based on comments above try
JsonConvert.DeserializeObject<Dictionary<string,dynamic>>(json)
seems to work even for complex objects and lists.
A bit late to the game, but non of the above solutions pointed me in the direction of a pure and simple .NET, no json.net solution. So here it is, ended up being very simple. Below a full running example of how it is done with standard .NET Json serialization, the example has dictionary both in the root object and in the child objects.
The golden bullet is this cat, parse the settings as second parameter to the serializer:
Full code below:
Json.NET does this...
More examples: Serializing Collections with Json.NET
Mark Rendle posted this as a comment, I wanted to post it as an answer since it's the only solution that has worked so far to return the success and the error-codes json results from the Google reCaptcha response.
Thanks again, Mark!