如何根据条件来确定某个字段是否应该被序列化

应用场景:

有的时候需要通过条件来判断某个字段是否可以被序列化,例如:再写WebApi的时候,只有当Api方法出错的时候,才将error的具体信息返回去,如果方法正常运行就不返回error字段。

第一种方式(JSON):

我们可以用JSON.NET的 ShouldSerialize 语法

public class Employee
{
    public string Name { get; set; }
    public Employee Manager { get; set; }

    public bool ShouldSerializeManager()
    {
        // don't serialize the Manager property if an employee is their own manager
        return (Manager != this);
    }
}

详细信息请看如下链接:

http://stackoverflow.com/questions/34304738/how-to-ignoring-fields-and-properties-conditionally-during-serialization-using-j

第二种方式(XML):

我们可以创建另外一个boolean类型标识字段,这个字段的名字格式为:目标字段名称 + Specified

当这个标识字段返回true时,目标字段将被序列化;反之将不会被序列化

当然,如果直接在目标字段上添加XmlIgnoreAttribute标签,则此目标字段也将不会被序列化

public class Person
{
    public string Name
    {
        get;
        set;
    }

    [XmlIgnore]
    public bool NameSpecified
    {
        get  { return Name != "secret"; }
    }
}

详细信息请看如下链接:

http://stackoverflow.com/questions/4386338/how-to-serialize-some-attribute-in-some-condition

原文地址:https://www.cnblogs.com/mingmingruyuedlut/p/5951423.html