2016-04-28 42 views
2

是否存在某些基於非屬性的方法來忽略序列化時沒有對應構造函數參數的所有屬性?例如,在序列化此類時,應忽略屬性Combo。對MyClass實例的往返序列化/反序列化不要求Combo被序列化。理想情況下,我可以使用一些開箱即用的設置。如何在序列化時自動忽略沒有對應構造函數參數的所有屬性

public class MyClass 
{ 
    public MyClass(int myInt, string myString) 
    { 
     this.MyInt = myInt; 
     this.MyString = myString; 
    } 

    public int MyInt { get; } 

    public string MyString { get; } 

    public string Combo => this.MyInt + this.MyString; 
} 
+0

如果構造函數中的參數名稱與屬性名稱相同,我認爲反射可以幫助您獲取應該序列化的屬性列表。然後你可以使用這個簡單的方法來創建非基於屬性的方法http://stackoverflow.com/questions/9377414/excluding-some-properties-during-serialization-without-changing-the-original-cla – AnotherGeek

回答

2

您可以用custom IContractResolver做到這一點:

public class ConstructorPropertiesOnlyContractResolver : DefaultContractResolver 
{ 
    readonly bool serializeAllWritableProperties; 

    public ConstructorPropertiesOnlyContractResolver(bool serializeAllWritableProperties) 
     : base() 
    { 
     this.serializeAllWritableProperties = serializeAllWritableProperties; 
    } 

    protected override JsonObjectContract CreateObjectContract(Type objectType) 
    { 
     var contract = base.CreateObjectContract(objectType); 

     if (contract.CreatorParameters.Count > 0) 
     { 
      foreach (var property in contract.Properties) 
      { 
       if (contract.CreatorParameters.GetClosestMatchProperty(property.PropertyName) == null) 
       { 
        if (!serializeAllWritableProperties || !property.Writable) 
         property.Readable = false; 
       } 
      } 
     } 

     return contract; 
    } 
} 

然後使用它像:

var settings = new JsonSerializerSettings { ContractResolver = new ConstructorPropertiesOnlyContractResolver(false) }; 
var json = JsonConvert.SerializeObject(myClass, Formatting.Indented, settings); 

trueserializeAllWritableProperties如果你也想序列化的讀/寫性能不包含在構造函數參數列表中,例如AnUnrelatedReadWriteProperty在:

public class MyClass 
{ 
    public MyClass(int myInt, string myString) 
    { 
     this.MyInt = myInt; 
     this.MyString = myString; 
    } 

    public int MyInt { get; private set; } 

    public string MyString { get; private set; } 

    public string Combo { get { return this.MyInt + this.MyString; } } 

    public string AnUnrelatedReadWriteProperty { get; set; } 
} 

注意您可能要cache your contract resolver for best performance

+0

哇,awsome回答!非常感謝花時間寫這篇文章。 – SFun28

相關問題