Order of fields when serializing the derived class in JSON.NET
According to the JSON standard, a JSON object is an unordered set of name/value pairs. So my recommendation would be to not worry about property order. Nevertheless you can get the order you want by creating your own ContractResolver
inheriting from one of the standard contract resolvers, and then overriding CreateProperties
:
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)
{
while (type != null)
{
yield return type;
type = type.BaseType;
}
}
}
And then use it like:
// Cache an instance of the resolver for performance
static IContractResolver baseFirstResolver = new BaseFirstContractResolver { /* Set any required properties here e.g. NamingStrategy = new CamelCaseNamingStrategy() */ };
// And use the cached instance when serializing and deserializing
var settings = new JsonSerializerSettings
{
ContractResolver = baseFirstResolver,
// Add your other settings here.
TypeNameHandling = TypeNameHandling.Objects
};
var json = JsonConvert.SerializeObject(derived, typeof(Base), Formatting.Indented, settings);
Notes:
This approach works especially well with multi-level type hierarchies as it automates correct ordering of properties from all levels in the hierarchy.
Newtonsoft recommends caching instances of contract resolvers for best performance.
Demo fiddle here.
Just as a complement, another approach different than the accepted answer is using [JsonProperty(Order = -2)]
; You can modify your base class as follow:
public class Base
{
[JsonProperty(Order = -2)]
public string Id { get; set; }
[JsonProperty(Order = -2)]
public string Name { get; set; }
[JsonProperty(Order = -2)]
public string LastName { get; set; }
}
The reason of setting Order values to -2 is that every property without an explicit Order value has a value of -1 by default. So you need to either give all child properties an Order value, or just set your base class' properties to -2.
If you're using ASP.NET Core, don't override important contract resolver settings provided by default. Following from @dbc's answer, you can do this:
class DataContractJsonResolver : DefaultContractResolver
{
public DataContractJsonResolver()
{
NamingStrategy = new CamelCaseNamingStrategy();
}
protected override IList<JsonProperty> CreateProperties( Type type, MemberSerialization memberSerialization )
{
return base.CreateProperties( type, memberSerialization )
.OrderBy( p => BaseTypesAndSelf( p.DeclaringType ).Count() ).ToList();
IEnumerable<Type> BaseTypesAndSelf( Type t )
{
while ( t != null ) {
yield return t;
t = t.BaseType;
}
}
}
}