proleskovskiy
proleskovskiy

Reputation: 31

C# JavaScriptSerializer - how to serialize as base type?

I have a problem serializing with JavaScriptSerializer. For example, I have a base class

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

and a derived class

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

How can I serialize an instance of MyDerivedClass as MyBaseClass? In case I don't want resulting JSON to contain Patronymic property? Is it possible?

Upvotes: 3

Views: 937

Answers (1)

Robert Fricke
Robert Fricke

Reputation: 3643

Well, it is possible to do pretty generic, with a little help of extension methods. Add this class to your project:

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 });
            }
        }
    }
}

You can then use this code to serialize MyDerivedClass as 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

Upvotes: 1

Related Questions