Serialize EntityFramework Object and Remove Null properties

In the following code, I'm providing a way to serialize an entity object from the EntityFramework taking into consideration the relationships with other entities. I'm providing a way to remove the empty properties, null values and empty arrays from the Json string.

First of all, it is important to mention that the following code is applicable only for Newtonsoft API, I'm using JsonConvert.SerializeObject for serialization.

Make sure to add a reference to the Newtonsoft.Json.dll.

Serialize Class object using Newtonsoft JSON serializer

In this sample code, we need to set Lazy Load and Proxy Creation of the EF DBContext to false to prevent cyclic serialization errors. The NullValueHandling will do the magic to remove the empty properties (other than the arrays) from the JObject.

using (MyDBEntities db = new MyDBEntities())
db.Configuration.LazyLoadingEnabled = false;
db.Configuration.ProxyCreationEnabled = false;
//Querying the database to get the account object with specific relationship entities
Account account = db.Account.Include("Address").Include("SocialLink").Include("Industry")
.Include("AccountType").Include(x => x.EntityTags).Where(x => x.ID == accountID).FirstOrDefault();
//Prepare the Json Serializer settings
JsonSerializerSettings JsonConvertDefaultSettings = new JsonSerializerSettings
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore, //used to remove empty or null properties
DefaultValueHandling = DefaultValueHandling.Ignore,
ContractResolver = new SkipEmptyContractResolver() //used to the empty arrays
JObject jsonData = JObject.Parse(JsonConvert.SerializeObject(account, JsonConvertDefaultSettings));
return jsonData;

As for the empty Arrays they require special handling to remove them. We are going to use the DefaultContractResolver to remove the empty arrays from the JObject:

public class SkipEmptyContractResolver : DefaultContractResolver
public new static readonly SkipEmptyContractResolver Instance = new SkipEmptyContractResolver();

protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
JsonProperty property = base.CreateProperty(member, memberSerialization);
property.ShouldSerialize = obj =>
if (property.PropertyType.Name.Contains("ICollection"))
return (property.ValueProvider.GetValue(obj) as dynamic).Count > 0;
return true;
return property;

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website