StackOverflow Q28674167

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
					
public class Program
{
	public static void Main()
	{
		List<Base> list = new List<Base>();
		
		list.Add( new Base { Id = 1, ParentId = -1 });
		list.Add( new Foo { Id = 2, ParentId = 1 });
		
		string json = JsonConvert.SerializeObject(list, Formatting.Indented);

		Console.WriteLine(json);
	}
}

class Base
{
	public int Id { get; set; }
	public int ParentId { get; set; }

	public virtual bool ShouldSerializeParentId()
	{
		return false;
	}
}

class Foo : Base
{
	public override bool ShouldSerializeParentId()
	{
		return true;
	}
}
;