// simple dummy object just showing what "MyObject" could potentially bepublic class MyObject{ public String Property1; public String Property2; public String Property3; public String Property4; public String Property5; public String Property6;}// custom converter that tells the serializer what to do when it sees one of// the "MyObject" types. Use our custom method instead of reflection and just// dumping properties.public class MyObjectConverter : JavascriptConverter{ public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavascriptSerializer serializer) { throw new ApplicationException("Serializable only"); } public override IDictionary<string, object> Serialize(object obj, JavascriptSerializer serializer) { // create a variable we can push the serailized results to Dictionary<string, object> result = new Dictionary<string, object>(); // grab the instance of the object MyObject myobj = obj as MyObject; if (myobj != null) { // only serailize the properties we want result.Add("Property1", myobj.Property1); result.Add("Property3", myobj.Property3); result.Add("Property5", myobj.Property5); } // return those results return result; } public override IEnumerable<Type> SupportedTypes { // let the serializer know we can accept your "MyObject" type. get { return new Type[] { typeof(MyObject) }; } }}然后在哪里进行序列化:
// create an instance of the serializerJavascriptSerializer serializer = new JavascriptSerializer();// register our new converter so the serializer knows how to handle our custom objectserializer.RegisterConverters(new JavascriptConverter[] { new MyObjectConverter() });// and get the resultsString result = serializer.Serialize(MyObjectInstance);


