如何根據條件來肯定某個字段是否應該被序列化

應用場景:this

有的時候須要經過條件來判斷某個字段是否能夠被序列化,例如:再寫WebApi的時候,只有當Api方法出錯的時候,纔將error的具體信息返回去,若是方法正常運行就不返回error字段。spa

 

第一種方式(JSON):code

咱們能夠用JSON.NET的 ShouldSerialize 語法blog

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);
    }
}

 

詳細信息請看以下連接:ci

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

 

第二種方式(XML):string

咱們能夠建立另一個boolean類型標識字段,這個字段的名字格式爲:目標字段名稱 + Specifiedit

當這個標識字段返回true時,目標字段將被序列化;反之將不會被序列化io

固然,若是直接在目標字段上添加XmlIgnoreAttribute標籤,則此目標字段也將不會被序列化class

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

相關文章
相關標籤/搜索