Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize only derived type using Newtonsoft Json.NET

Tags:

c#

json.net

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;}
}
like image 478
Saran Avatar asked Sep 14 '25 15:09

Saran


1 Answers

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.

like image 164
Ismail Hawayel Avatar answered Sep 16 '25 08:09

Ismail Hawayel