DataContract surrogate for amplified value type
Asked Answered
P

1

2

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?

Plume answered 9/11, 2011 at 21:58 Comment(1)
Another info: the surrogate cast exception happens with an amplified Guid.Plume
E
2

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 https://learn.microsoft.com/en-us/archive/blogs/carlosfigueira/wcf-extensibility-serialization-callbacks.

Earthaearthborn answered 15/11, 2011 at 14:32 Comment(2)
Thx. That explains a lot. We solved the issue by using another serializer (Json.Net) by now.Plume
@Carlosfigueira thanks you helped me answer part of my question but if you had anymore insite on this it would be greatly appreciatedFaraway

© 2022 - 2024 — McMap. All rights reserved.