使用JavaScriptSerializer进行序列化时,可以忽略类的某些字段吗?
使用JavaScriptSerializer进行序列化时,我们可以更改字段名称吗?
例如,该字段是字符串is_OK,但我想将其映射到isOK吗?

最佳答案

为了获得最大的灵活性(因为还提到了名称),理想的做法是在RegisterConverters对象上调用JavaScriptSerializer,注册一个或多个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<string, object> dictionary, System.Type type, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }
        public override System.Collections.Generic.IEnumerable<System.Type> SupportedTypes
        {
            get { yield return typeof(Foo); }
        }
        public override System.Collections.Generic.IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            var data = new Dictionary<string, object>();
            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);
    }
}

关于c# - 有关JavaScriptSerializer的一些问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4151913/

10-11 02:36