Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

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:

  1. I don't want to implement my own JSON parser
  2. Can't use ASP.NET 4.0 yet
  3. Would prefer to stay away from the older, deprecated ASP.NET class for JSON
like image 918
richardtallent Avatar asked Jul 30 '09 16:07

richardtallent


People also ask

How do I deserialize JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

How do you serialize and deserialize an object in C# using JSON?

It returns JSON data in string format. In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data.

How do you represent a dictionary in JSON?

Introducing JSON JSON is a way of representing Arrays and Dictionaries of values ( String , Int , Float , Double ) as a text file. In a JSON file, Arrays are denoted by [ ] and dictionaries are denoted by { } .


2 Answers

Json.NET does this...

string json = @"{""key1"":""value1"",""key2"":""value2""}";  var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); 

More examples: Serializing Collections with Json.NET

like image 100
James Newton-King Avatar answered Oct 02 '22 08:10

James Newton-King


I did discover .NET has a built in way to cast the JSON string into a Dictionary<String, Object> via the System.Web.Script.Serialization.JavaScriptSerializer type in the 3.5 System.Web.Extensions assembly. Use the method DeserializeObject(String).

I stumbled upon this when doing an ajax post (via jquery) of content type 'application/json' to a static .net Page Method and saw that the method (which had a single parameter of type Object) magically received this Dictionary.

like image 20
Crispy Avatar answered Oct 02 '22 06:10

Crispy