How to force Newtonsoft Json to serialize all properties? (Strange behavior with “Specified” property)

This behavior is mentioned, very briefly, in the Json.NET 4.0.1 release notes: New feature – Added XmlSerializer style Specified property support. The XmlSerializer functionality is in turn described in MinOccurs Attribute Binding Support:

[For optional fields] Xsd.exe generates a public field of type bool whose name is the element field’s name with Specified appended. For example, if the element field’s name is startDate, the bool field’s name becomes startDateSpecified. When serializing an object to XML, the XmlSerializer class checks the value of the bool field to determine whether to write the element.

I feel as though this functionality should be documented here, but is not. You might want to open a documentation issue with Newtonsoft.

Since you don’t want this behavior, if you are using Json.NET 11.0.1 or later, you can disable it for all classes by instantiating your own DefaultContractResolver and settting DefaultContractResolver.IgnoreIsSpecifiedMembers = true:

public static class JsonContractResolvers
{
    // Newtonsoft recommends caching and reusing contract resolvers for best performance:
    // https://www.newtonsoft.com/json/help/html/Performance.htm#ReuseContractResolver
    // But be sure not to modify IgnoreIsSpecifiedMembers after the contract resolver is first used to generate a contract.

    public static readonly DefaultContractResolver IgnoreIsSpecifiedMembersResolver =
        new DefaultContractResolver { IgnoreIsSpecifiedMembers = true };
}

Then pass it to JsonConvert as follows:

var settings = new JsonSerializerSettings { ContractResolver = JsonContractResolvers.IgnoreIsSpecifiedMembersResolver };
var json = JsonConvert.SerializeObject(testObject, Formatting.Indented, settings);

Or to create a JToken do:

var jToken = JToken.FromObject(testObject, JsonSerializer.CreateDefault(settings));

If you are using an earlier version, you will need to create and cache a custom contract resolver:

public static class JsonContractResolvers
{
    public static readonly DefaultContractResolver IgnoreIsSpecifiedMembersResolver =
        new IgnoreSpecifiedContractResolver();
}

internal class IgnoreSpecifiedContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        property.GetIsSpecified = null;
        property.SetIsSpecified = null;
        return property;
    }
}

Leave a Comment