.NET 3.5: 使用DataContractJsonSerializer进行JSON 序列化
InASP.NET AJAX Extensions v1.0 for ASP.NET 2.0 there is the JavaScriptSerializer class that provides JSONserialization and deserialization functionality. However,in .NET 3.5 the JavaScriptSerializer has been marked obsolete. The new object to use for JSON serialization in .NET 3.5 is the DataContractJsonSerliaizer object. I'm still new to the DataContractJsonSerializer,but here's a summary of what I've learned so far... Object to Serialize Here's a simple Person object with First Name and Last Name properties. public class Person Now in orderto serialize our objectto JSONusing the DataContractJsonSerializer wemust either mark it with the Serializable attribute or the DataContract attribute. If we mark the class with the DataContract attribute,then we must mark each property we want serialized with the DataMember attribute. /// Marked with the Serializable Attribute
Serialization Code Jere's the most basic code to serialize our object to JSON: Person myPerson = new Person("Chris","Pietschmann"); Our resulting JSON looks like this: /// Result of Person class marked as Serializable
As you can see the first serialization with the class markedwith theSerializable attribute isn't quite what we were expecting,but is still JSON.This serialization actually isn't compatible with the client-side JSON Serializer in ASP.NET AJAX. As you can see the second serialization with the class marked with the DataContract attribute is exactly what we were expecting,and is the same JSON that the old JavaScriptSerializer object would have generated. This is the method of JSON serialization using the DataContractJsonSerializer that you'll need to do if you are going to pass the resulting JSON down to the client to be consumed with ASP.NET AJAX.
Deserialization Code Here's the most basic code to deserialize our object from JSON: Person myPerson = new Person();
Controlling the property names in the resulting JSON When using the DataContract and DataMember attributes,you can tell the DataMember attribute the specific name you want that property to have within the JSON serialization by setting its "Name" named parameter. Here's an example that will give the name of "First" to the "FirstName" property within the JSON serialization: [DataMember(Name = "First")] The resulting JSON looks like this:
{"First":"Chris","LastName":"Pietschmann"}
Here's the code for some Helper methods using Generics to do all the dirty work for you using System.Runtime.Serialization;
What Assembly References does my application need for this? From the namespace that containsDataContractJsonSerializer you can probably tell that you need to add a reference to the System.Runtime.Serialization assembly. However,you also need to add a reference to the System.ServiceModel.Web assembly. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |