Question

I know that I can omit a property with JsonIgnore attribute or with IgnoreDataMember if my class it's decorated with DataContract attribute. In particulary I use the latter method but I see the property in json.

What's my error?

My class:

[DataContract(Name="Activity")]
public class ActivityDTO
{
    [DataMember(Name = "id")]
    public int Id { get; set; }
    [DataMember(Name="usercode")]
    [IgnoreDataMember] 
    public string UserCode { get; set; }
    [DataMember(Name = "value")]
    public string Value { get; set; }
}

and Json

{
        "id": 5,
        "usercode": "user",
        "value": "100"
}

I want use usercode in deserialization and don't see it in serialization

Was it helpful?

Solution

The answer is in this article.

The IgnoreDataMemberAttribute attribute is only honored when used with unmarked types. This includes types that are not marked with one of the DataContractAttribute, SerializableAttribute, CollectionDataContractAttribute, or EnumMemberAttribute attributes, or marked as serializable by any other means (such as IXmlSerializable).

In your case, to omit the UserCode property - just do not mark with any serialization attributes:

[DataContract(Name="Activity")]
public class ActivityDTO
{
    [DataMember(Name = "id")]
    public int Id { get; set; }
    public string UserCode { get; set; }
}

Added: As you want deserialization to behave differently from serialization, I see 2 ways to achieve this:

a) described here: How can I prevent a datamember from being serialized The disadvantage is that it is not thread-safe.

[DataContract( Name = "Activity" )]
public class ActivityDTO
{
    private string _userCode;

    [DataMember( Name = "id" )]
    public int Id { get; set; }

    [DataMember( Name = "usercode" , EmitDefaultValue = false )]
    public string UserCode { get; set; }

    [DataMember( Name = "value" )]
    public string Value { get; set; }

    [OnSerializing]
    private void OnSerializing( StreamingContext context )
    {
        _userCode = UserCode;
        UserCode = default( string );
    }

    [OnSerialized]
    private void OnSerialized( StreamingContext context )
    {
        UserCode = _userCode;
    }

}

b) you can go custom all the way and implement ISerializable:

[Serializable]
public class ActivityDTO : ISerializable
{
    public int Id { get; set; }
    public string UserCode { get; set; }
    public string Value { get; set; }

    public ActivityDTO()
    {
    }

    public ActivityDTO( SerializationInfo info , StreamingContext context )
    {
        Id = info.GetInt32( "id" );
        UserCode = info.GetString( "usercode" );
        Value = info.GetString( "value" );
    }

    public void GetObjectData( SerializationInfo info , StreamingContext context )
    {
        info.AddValue( "id" , Id );
        info.AddValue( "value" , Value );
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top