How can I do JSON serializer ignore navigation properties?

CSharp · Console

/Program.cs

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
			
public class Program
{
	// Ramin Bateni
	// This code related to my answer in Stackoverflow 
	// here >> https://stackoverflow.com/questions/26162902/how-can-i-do-json-serializer-ignore-navigation-properties/32797274?noredirect=1#comment104684486_32797274
	public static void Main()
	{
		JsonSerializerSettings settings = new JsonSerializerSettings
			{
				// ContractResolver = new CustomResolver();
				// OR:
				ContractResolver = new CustomResolver(new []
				{
					// keep Lib property between virtual properties
					nameof(PC.Libs),
					// keep Files property between virtual properties
					nameof(PC.Files)
				}),
				PreserveReferencesHandling = PreserveReferencesHandling.None,
				ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
				Formatting = Formatting.Indented
			};

			// -------------------------------------------------------------------
			// Do the serialization and output to the console
			var pc=new PC();
			var json = JsonConvert.SerializeObject(pc, settings);
		
			Console.WriteLine(json);
		}


	}

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

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