You could create a custom contract resolver which would allow you to make adjustments to the properties and set them to ignore where an XmlIgnoreAttribute is set.
public class CustomContractResolver : DefaultContractResolver
{
private readonly JsonMediaTypeFormatter formatter;
public CustomContractResolver(JsonMediaTypeFormatter formatter)
{
this.formatter = formatter;
}
public JsonMediaTypeFormatter Formatter
{
[DebuggerStepThrough]
get { return this.formatter; }
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
this.ConfigureProperty(member, property);
return property;
}
private void ConfigureProperty(MemberInfo member, JsonProperty property)
{
if (Attribute.IsDefined(member, typeof(XmlIgnoreAttribute), true))
{
property.Ignored = true;
}
}
}
You can use apply this custom resolver by setting the ContractResolver property of the JsonSerializerSettings when serializing an object
https://www.newtonsoft.com/json/help/html/ContractResolver.htm
string json =
JsonConvert.SerializeObject(
product, // this is your object that has xml attributes on it that you want ignored
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CustomResolver() }
);
If you're using WebApi you can set it globally to apply to all contracts.
var config = GlobalConfiguration.Configuration;
var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.ContractResolver = new CustomContractResolver();