Is there any JsonSerializerSettings available for serializing only the derived type.
for example consider i have below two class. When I am serializing Employee object the the result json should only contains the properties of employee not the person class.
public class Person
{
public string Name { get; set; }
}
public class Employee : Person
{
public DateTime JoiningDate { get; set; }
public string EmployeeId { get; set;}
}
Questions like those usually reflect an issue with model design, however, one way to do what you want to do is to get rid of the inheritance; you could try something like converting your object to dynamic and then serialize the dynamic object :
class MyJson
{
public static string SerializeObject<T>(T obj, bool ignoreBase)
{
if (!ignoreBase)
{
return JsonConvert.SerializeObject(obj);
}
var myType = typeof(T);
var props = myType.GetProperties().Where(p => p.DeclaringType == myType).ToList();
var x = new ExpandoObject() as IDictionary<string, Object>;
props.ForEach(p => x.Add(p.Name, p.GetValue(obj, null)));
return JsonConvert.SerializeObject(x);
}
}
call it like
MyJson.SerializeObject<Employee>(e, true)
This way you can use it for any type and filter the properties to serialize however you wish in the helper class. For example, you can check the property attributes and decided if it should be added to the dynamic object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With