using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class BaseFirstContractResolver : DefaultContractResolver
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) =>
base.CreateProperties(type, memberSerialization)
?.OrderBy(p => p.DeclaringType.BaseTypesAndSelf().Count()).ToList();
public static class TypeExtensions
public static IEnumerable<Type> BaseTypesAndSelf(this Type type)
public string Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public class Middle : Base
public string MidProperty { get; set; }
public class Derived : Middle
public string Address { get; set; }
public DateTime DateOfBirth { get; set; }
static IContractResolver baseFirstResolver = new BaseFirstContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() };
public static void Test()
var derived = new Derived { Address = "test", DateOfBirth = DateTime.Today, Id = "007", Name = "test name", LastName = "test last name", MidProperty = "MidProperty value" };
var settings = new JsonSerializerSettings
ContractResolver = baseFirstResolver,
TypeNameHandling = TypeNameHandling.Objects
var json = JsonConvert.SerializeObject(derived, typeof(Base), Formatting.Indented, settings);
Assert.IsTrue(new[] { "id", "name", "last_name", "mid_property", "address", "date_of_birth" }.SequenceEqual(JObject.Parse(json).Properties().Select(p => p.Name).Where(n => n != "$type")));
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];