应该使用Xml和Json序列化

时间:2019-01-10 18:41:13

标签: c# xml-serialization jsonserializer

当我使用XmlSerialize时,我正在使用ShouldSerialize方法有条件地序列化字段。但是现在我需要使用Json序列化相同的类,但是我希望在使用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>

结果杰森:

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

两者都应使用ShouldSerializeLastName方法,但是,我希望在Json中将其忽略,并且将显示所有字段。

1 个答案:

答案 0 :(得分:2)

您可以使用自己的ShouldSerialize*() conditional serialization并设置contract resolver来禁用Json.NET对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);

注意:

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

  • 因为合同解析器会缓存类型信息,因此不建议在构造已有的合同解析器并用于生成合同后修改其属性。

  • IgnoreShouldSerializeMembers是Json.NET 11.0.1中引入的。

提琴here