您可以用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);
通true
爲serializeAllWritableProperties
如果你也想序列化的讀/寫性能不包含在構造函數參數列表中,例如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。
來源
2016-04-28 15:13:52
dbc
如果構造函數中的參數名稱與屬性名稱相同,我認爲反射可以幫助您獲取應該序列化的屬性列表。然後你可以使用這個簡單的方法來創建非基於屬性的方法http://stackoverflow.com/questions/9377414/excluding-some-properties-during-serialization-without-changing-the-original-cla – AnotherGeek