关于JavaScriptSerializer的一些问题

  1. 使用JavaScriptSerializer进行序列化时,是否可以忽略该类的某些字段?

  2. 使用JavaScriptSerializer进行序列化时,我们可以更改字段的名称吗? 例如,字段是字符串is_OK,但我想将它映射到isOK?

为了获得最大的灵活性(因为你也提到了名字),理想的情况是在JavaScriptSerializer对象上调用RegisterConverters ,注册一个或多个JavaScriptConverter实现(可能在数组或迭代器块中)。

然后,您可以通过向返回的字典添加键/值对,实现Serialize以在任何名称下添加(或不添加)和值。 如果数据是双向的,您还需要匹配的Deserialize ,但通常(对于ajax服务器)这不是必需的。

完整示例:

 using System; using System.Collections.Generic; using System.Web.Script.Serialization; class Foo { public string Name { get; set; } public bool ImAHappyCamper { get; set; } private class FooConverter : JavaScriptConverter { public override object Deserialize(System.Collections.Generic.IDictionary dictionary, System.Type type, JavaScriptSerializer serializer) { throw new NotImplementedException(); } public override System.Collections.Generic.IEnumerable SupportedTypes { get { yield return typeof(Foo); } } public override System.Collections.Generic.IDictionary Serialize(object obj, JavaScriptSerializer serializer) { var data = new Dictionary(); Foo foo = (Foo)obj; if (foo.ImAHappyCamper) data.Add("isOk", foo.ImAHappyCamper); if(!string.IsNullOrEmpty(foo.Name)) data.Add("name", foo.Name); return data; } } private static JavaScriptSerializer serializer; public static JavaScriptSerializer Serializer { get { if(serializer == null) { var tmp = new JavaScriptSerializer(); tmp.RegisterConverters(new [] {new FooConverter()}); serializer = tmp; } return serializer; } } } static class Program { static void Main() { var obj = new Foo { ImAHappyCamper = true, Name = "Fred" }; string s = Foo.Serializer.Serialize(obj); } } 

您可以使用[ScriptIgnore]跳过属性:

 using System; using System.Web.Script.Serialization; public class Group { // The JavaScriptSerializer ignores this field. [ScriptIgnore] public string Comment; // The JavaScriptSerializer serializes this field. public string GroupName; } 

我会使用匿名类型来保持生成的JSON清洁。

 class SomeClass { public string WantedProperty { get; set; } public string UnwantedProperty { get; set; } } var objects = new List(); ... new JavaScriptSerializer().Serialize( objects .Select(x => new { x.WantedProperty }).ToArray() );