How to decode a JSON string using C#?

The Mask picture The Mask · Oct 8, 2011 · Viewed 31.6k times · Source

I'm looking for an example code/lib to decode a JSON string using C#.

To encode I can do this:

var data = new Dictionary<string,string>(); 
data.Add("..", "..."); 
var json_encoded = new JavaScriptSerializer().Serialize(data); 

but how do I decode?

var json_decoded = ?? 

Answer

Kakashi picture Kakashi · Oct 9, 2011

You can do this:

var data = new Dictionary<string, string>();
data.Add("foo", "baa"); 

JavaScriptSerializer ser = new JavaScriptSerializer();
var JSONString = ser.Serialize(data); //JSON encoded

var JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); //JSON decoded
Console.Write(JSONObj["foo"]); //prints: baa