:次に
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