放大值类型的 DataContract 代理
我想在 DataContract 类中使用自定义扩展类型(认为可以为 Nullable)。 我尝试编写一个 IDataContractSurrogate
但在反序列化时失败。
我的放大类型如下所示:
public struct Amplified<TValue>
{
public TValue Value { get; set; }
//... some special code ...
}
并且 DataContract 可能如下所示:
[DataContract] public class MyDTO
{
[DataMember] public Amplified<string> SpecialString { get; set; }
}
上面的代码可以工作,但会与放大类型的 Value 属性产生不必要的嵌套。我希望 DataContract 将 Ampliefied 表示为电线上的普通字符串。
使用 DataContract 序列化程序(JSON 和 Xml)可以实现这一点吗? 为什么在使用 IDataContractSurrogate 将 Amplified 替换为字符串时出现 InvalidCastException?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能对原始类型使用代理(即,当 T 是原始类型时,您可以从
Amplified
转换为T
,但不能从另一个方向转换) 。对于可能的替代方案,请查看https://learn.microsoft.com/en-us/archive/blogs/carlosfigueira/wcf-extensibility-serialization-callbacks。You cannot use surrogates for primitive types (i.e., you'll be able to convert from
Amplified<T>
toT
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.