2

I want to ignore certain properties in a class, but I want to keep the class POCO for many reasons. Hence I do not want to introduce dependency to Json.NET, and do not want to use JsonIgnoreAttribute.

Is there some way to customize the contract resolver to respect some other convention? Eg, properties that are named starting with the word "NonSerialized", for instance, or at least a custom attribute of our own choosing that is internally created (again to eliminate external dependency and keep the domain model as pure as possible).

Also different persistence will need to ignore/respect the same attribute differently, so it would be nice to be able to control what gets serialized at runtime via some kind of fluent api. Is this even possible?

4

1 に答える 1

3

フィールドの場合[NonSerializable]、システム名前空間の属性を使用して、シリアル化を回避できます。そうすれば、外部ライブラリに依存しなくなります。これはプロパティでは機能しません。

プロパティには、 Conditional Property Serializationという機能があります。基本的に、ブール値を返し、命名規則に従うメソッドを実装します - ShouldSerialize[PropertyName]

public class LoginModel
{
    public string UserName { get; set; }

    public string Password { get; set; }

    public bool RememberMe { get; set; }

    public bool ShouldSerializePassword() { return false; }
}

この例では、常にシリアル化を回避しPasswordます。ShouldSerializeメソッドには、単純に false を返すのではなく、より複雑な検証ロジックを含めることができます。

于 2013-03-11T09:46:39.643 に答える