如何使 ShouldSerialize*() 仅适用于 XML 而不是 JSON 序列化?

How can I make ShouldSerialize*() apply only to XML and not JSON serialization?

我在使用 XmlSerializer 时使用 ShouldSerialize 方法有条件地序列化字段。但是现在我需要使用 JSON 序列化相同的 class,但是我希望在使用 JSON 时忽略 ShoulSerialize 方法,我可以用任何方式做到这一点吗?

[TestClass]
public class UnitTest1
{
    private readonly Customer _customer = new Customer
        {
            FirstName = "Paulo",
            LastName = "Balbino",
            Age = 25
        };

    [Serializable]
    public class Customer
    {
        [XmlElement("FirstName")]
        public string FirstName { get; set; }

        [XmlElement("LastName")]
        public string LastName { get; set; }

        [XmlElement("Age")]
        public int Age { get; set; }

        public bool ShouldSerializeLastName()
        {
            return Age > 30; // Enter here only if it is XmlSerialize.
        }
    }

    [TestMethod]
    public void XmlSerialize()
    {
        try
        {
            var xmlSerializer = new XmlSerializer(typeof(Customer));

            using (var textWriter = new StringWriter())
            {
                xmlSerializer.Serialize(textWriter, _customer);
                Debug.WriteLine(textWriter.ToString());
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
    }

    [TestMethod]
    public void JsonConvert()
    {
        try
        {
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(_customer);
            Debug.WriteLine(json);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
    }
}

结果Xml:

<?xml version="1.0" encoding="utf-16"?>
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>Paulo</FirstName>
  <Age>25</Age>
</Customer>

结果Json:

{"FirstName":"Paulo","Age":25}

两者都转到 ShouldSerializeLastName() 方法,但是,我希望在 JSON 中忽略它并显示所有字段。

您可以禁用 Json.NET 对 ShouldSerialize*() conditional serialization by using your own contract resolver and setting DefaultContractResolver.IgnoreShouldSerializeMembers = true 的支持。

首先,分配一个合约解析器如下:

static DefaultContractResolver IgnoreShouldSerializeContractResolver = new DefaultContractResolver
{
    IgnoreShouldSerializeMembers = true,
    //Set other properties as required, e.g.:
    //NamingStrategy = new CamelCaseNamingStrategy(),
};

然后使用如下:

var settings = new JsonSerializerSettings
{
    ContractResolver = IgnoreShouldSerializeContractResolver,
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(_customer, settings);

备注:

  • 您可能希望 以获得最佳性能,因为它只为每种类型生成一次合同信息,然后将其缓存。

  • 因为合同解析器缓存类型信息,所以不建议在 pre-existing 合同解析器构建并用于生成合同后修改其属性。

  • IgnoreShouldSerializeMembers 已在 Json.NET 11.0.1 中引入。

示例 fiddle here.