DataContract surrogate for amplified value type

2019-07-16 04:51发布

问题:

I want to use a custom aplified type (think Nullable) in a DataContract class. I tried to write a IDataContractSurrogate but it fails at deserialization.

My amplified type looks like this:

public struct Amplified<TValue>
{
    public TValue Value { get; set; }
    //... some special code ...
}

And a DataContract may look like this:

[DataContract] public class MyDTO
{
     [DataMember] public Amplified<string> SpecialString { get; set; }
}

The above code works but produces unnecessary nesting with the Value property of amplified type. I want the DataContract to represent the Ampliefied just as a normal string on the wire.

Is this possible with the DataContract Serializers (JSON & Xml)? Why do i get a InvalidCastException when using IDataContractSurrogate to replace Amplified with string?

回答1:

You cannot use surrogates for primitive types (i.e., you'll be able to convert from Amplified<T> to T when T is a primitive, but not the other direction). For a possible alternative, take a look at the section "Fine grained control of serialization format for primitives" at http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/06/wcf-extensibility-serialization-callbacks.aspx.