Is there an easy/elegant parser for dealing with JSON in C#? How about actually serializing/deserializing into C# objects?
5 Answers
var jss = new JavaScriptSerializer();
var data = jss.Deserialize<dynamic>(jsonString);
Don't forget to reference "System.Web.Extensions"
Comments
See
Basically you can use the 'data contract' model (that's often used for WCF XML serialization) for JSON as well. It's pretty quick and easy to use standalone for little tasks, I have found.
Also check out this sample:
Comments
There's the DataContractJsonSerializer class.
Deserialize:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MyObject));
Stream s = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json_string));
MyObject obj = ser.ReadObject(s) as MyObject;
Serialize:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MyObject));
Stream s = new MemoryStream();
MyObject obj = new MyObject { .. set properties .. };
ser.WriteObject(s, obj);
s.Seek( SeekOrigin.Begin );
var reader = new StreamReader(s);
string json_string = reader.ReadToEnd();
Comments
DataContractJsonSerializer for serializing to/from objects.
In Silverlight 3, there's System.Json (http://msdn.microsoft.com/en-us/library/system.json(VS.95).aspx), very handy.
System.Web.Script.Serialization.JavaScriptSerializeris applicable to this question (msdn.microsoft.com/en-us/library/…)? I'm very curious.