3

I have a class with property that i want use in json deserialization but i want omit in json serialization.

Example: I have a class user:

public class UserDTO
    {
        public string UserName { get; set; }
        public string Password { get; set; }

    }

and I use it in ASP.NET Web API.

I use this class for login and for get all users. Obviously, in get I want see only username, but in login I need username and password.

I have try to use attribute [IgnoreDataMember]:

public class UserDTO
{
   public string UserName { get; set; }
   [IgnoreDataMember]
   public string Password { get; set; }

}

or decorate my class with DataContract

[DataContract]
public class UserDTO
    {
       [DataMember]
       public string UserName { get; set; }

       public string Password { get; set; }

    }

but in this mode I can't login, indeed if I don't use attribute [DataContract] or [IgnoreDataMember] I can use login, but in get I see password.

I try also [NotSerialized] using backing field, like suggest here, but I obtain the same result.

Community
  • 1
  • 1
pask23
  • 714
  • 11
  • 20
  • Which serializer? It matters. – Marc Gravell Apr 04 '14 at 11:20
  • How can you deserialize a property you never serialize? By definition, you cannot operate on a property that doesn't exist! Also, if this behavior is for security than why are you using string? The main thing I don't understand is what actually is the problem? If you don't serialize the password on transmit, then by definition the receiver won't get a password. So your code is technically working as intended. So is the issue not preserving the password or preserving it? It sounds to me like you need to create a credentialDTO that holds a user and password to keep the two entities separate. – Tezra Apr 01 '19 at 20:28

1 Answers1

2

Depending on the serializer, you might be able to simply add:

public bool ShouldSerializePassword() { return false; }

This is a well-known pattern that works on many serializers, but not all.

Another common pattern is:

public bool PasswordSpecified { get { return false; } set {} }

But that is trickier as you need to also tell the serializer to ignore it - for example with [XmlIgnore, ScriptIgnore, IgnoreDataMember], etc.

Either way, you probably want to add:

[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]

(to prevent the property or method appearing in too many places)

One final option is simply: when serializing, don't give .Password a value ;p

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900