It is a useful question๐ and I hope this help:
A)
If you have created your models manually (without Entity Framework
), mark the relation properties as virtual
first.
If your models were created by EF
, It has already done it for you and each Relation Property
is marked as virtual
, as seen below:

Sample class:
public class PC
{
public int FileFolderId {get;set;}
public virtual ICollection<string> Libs { get; set; }
public virtual ICollection<string> Books { get; set; }
public virtual ICollection<string> Files { get; set; }
}
B)
Those relation properties can now be ignored by the JSON
serializer by using the following ContractResolver
for JSON.NET
:
CustomResolver:
class CustomResolver : DefaultContractResolver
{
private readonly List<string> _namesOfVirtualPropsToKeep=new List<string>(new String[]{});
public CustomResolver(){}
public CustomResolver(IEnumerable<string> namesOfVirtualPropsToKeep)
{
this._namesOfVirtualPropsToKeep = namesOfVirtualPropsToKeep.Select(x=>x.ToLower()).ToList();
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
var propInfo = member as PropertyInfo;
if (propInfo != null)
{
if (propInfo.GetMethod.IsVirtual && !propInfo.GetMethod.IsFinal
&& !_namesOfVirtualPropsToKeep.Contains(propInfo.Name.ToLower()))
{
prop.ShouldSerialize = obj => false;
}
}
return prop;
}
}
C)
Finally, to serialize your model easily use the above ContractResolver
. Set it up like this:
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new CustomResolver(new []
{
nameof(PC.Libs),
nameof(PC.Files)
}),
PreserveReferencesHandling = PreserveReferencesHandling.None,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented
};
var json = JsonConvert.SerializeObject(new PC(), settings);
Console.WriteLine(json);
Now, all the navigation (relation) properties [virtual
properties] will be ignored automatically except you keep some of them by determine them in your code.๐
Thanks from @BrianRogers for his answer here.
True
&False
values ofLazyLoadingEnabled
property. โ RAM