1

I'm trying to deserialize json to RequestWithDefault object

JSON:

{
  "fields":["f1","f2"]
}

My simple class diagram:

[DataContext]
public abstract class BaseRequest
{
  [DataMember]
  public virtual List<string> Fields { get; set; }
}

[DataContext]
public class RequestWithDefault : BaseRequest
{
  [DataMember]
  public override List<string> Fields {get; set; } = new List<string> {"test"}
}

After deserializing json to RequestWithDefault object Fields property contains ["test", "f1", "f1"]. I want to be sure that this default values are applied only in case when Fields were not specified in request, or was specified as null. How I can do this? I tried with [OnDeserializing] attribute but without success. Result is the same

According to this: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/collection-types-in-data-contracts Looks like during deserialization DataContractSerializer calling Add method from collection. That's why I have also default value and rest of items are added. When I will replace List<string> to string[] everything works fine.

Emil
  • 171
  • 1
  • 8

1 Answers1

1

It seems WCF serialization never use setter to set the value of the DataMember with type of collection, but use Add instead. Because of this, the only way to check whether the fields has any value is to check after it has been deserialized (not while deserializing).

[DataContext]
public abstract class BaseRequest
{
  [DataMember]
  public virtual List<string> Fields { get; set; }
}

[DataContext]
public class RequestWithDefault : BaseRequest
{
    [System.Runtime.Serialization.OnDeserialized]
    void OnDeserialized(System.Runtime.Serialization.StreamingContext c)
    {
        if (Fields == null
            || Fields.Count < 1)
        {
            Fields = new List<string> { "test" };
        }
    }
}
hendryanw
  • 1,819
  • 5
  • 24
  • 39
  • Somehow if I'm implementing this in that way setter is never called. I'm always getting default value. – Emil Mar 21 '18 at 06:56
  • @Emil I've updated my answer to reflect based on your comments, I hope this one works for you. – hendryanw Mar 21 '18 at 07:27
  • 1
    It should work. I was thinking about this solution after I found that Serializer not calling setters at all. I will create some protected method to set defaults. Thanks – Emil Mar 21 '18 at 07:29