C#JavaScriptSerializer - 如何序列化为基类型?

时间:2014-06-14 20:13:14

标签: c# javascriptserializer

我在使用JavaScriptSerializer进行序列化时遇到问题。 例如,我有一个基类

public class MyBaseClass{
    public int Id { get; set; }
    public string Name { get; set; }
}

和派生类

public class MyDerivedClass : MyBaseClass {
    public string Patronymic { get; set; }
}

如何将MyDerivedClass的实例序列化为MyBaseClass? 如果我不希望生成的JSON包含Patronymic属性? 有可能吗?

1 个答案:

答案 0 :(得分:1)

嗯,在扩展方法的帮助下,可以做到非常通用。将此类添加到项目中:

public static class Extensions
{
    //Takes one object and return a new object with type T
    public static T ToType<T>(this object value) where T : new()
    {
        var newValue = (T)Activator.CreateInstance(typeof(T));
        SetProperties(value, newValue);
        return newValue;
    }

    //Sets all properties with same name, from one source to target
    private static void SetProperties(object source, object target)
    {
        var targetType = target.GetType();
        var targetProperties = targetType.GetProperties();
        foreach (var prop in source.GetType().GetProperties())
        {
            if (targetProperties.Any(p => p.Name == prop.Name))
            {
                var propGetter = prop.GetGetMethod();
                var propSetter = targetType.GetProperty(prop.Name).GetSetMethod();
                var valueToSet = propGetter.Invoke(source, null);
                propSetter.Invoke(target, new[] { valueToSet });
            }
        }
    }
}

然后,您可以使用此代码将MyDerivedClass序列化为MyBaseClass

var myDerivedObj = new MyDerivedClass { Id = 1, Name = "Test", Patronymic = "Patronymic" };
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var myDerivedString = serializer.Serialize(myDerivedObj);
var myBaseObj = myDerivedObj.ToType<MyBaseClass>(); //Converting
var myBaseString = serializer.Serialize(myBaseObj); //This string is what you want