DataMember 发出默认值
我有一个 .Net Web 服务函数,可以接受一个字符串。
然后该函数会将该字符串序列化为 JSON,但我只想在它的值不是“”时序列化它。
我找到了这些说明:
http://msdn.microsoft.com/en-us/ library/aa347792.aspx
[DataContract]
public class MyClass
{
[DataMember (EmitDefaultValue=false)]
public string myValue = ""
}
不幸的是,我无法从序列化中隐藏 myValue,因为“”不是字符串的 .Net 默认值(这有多愚蠢!)
两个之一选项发生
在 Web 服务上有某种属性将“”设置为 null
在类上有一些条件
我更喜欢第一个,因为它使代码更干净,但意见会很棒。
谢谢
I have a .Net Web Service function that can accept one string.
That function will then serialize that string to JSON, but I only want to serialize it if it's value is not "".
I found these instructions:
http://msdn.microsoft.com/en-us/library/aa347792.aspx
[DataContract]
public class MyClass
{
[DataMember (EmitDefaultValue=false)]
public string myValue = ""
}
Unfortunatelly I can not hide the myValue from the serialization because "" is not the .Net default value for a string (how dumb is that!)
One of two option ocurred
On the web service have some kind of attribute that sets the "" to null
Have some condition on the class
I would prefer the 1st because it makes the code cleaner but an opinion would be great.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
DefaultValueAttribute
类:You can explicitly set what the default value is (for the purposes of serialization) using the
DefaultValueAttribute
class:我认为你在这里至少有几个选择。这是额外的工作,但值得。
您可以将字符串封装在引用类型中。由于引用类型如果不存在则为 null,因此您可以立即知道字符串是否存在(因为无论字符串是否为非空,封装引用类型都将为非 null 或 null。)
最后一个选择是添加一个额外的补充变量(可能是一个布尔值),该变量在 OnDeserializing/OnDeserialized/OnSerializing/OnSerialized 上设置,并使用它来跟踪某些内容是否实际存在电线。例如,您可以仅在实际序列化非空字符串时将此互补变量设置为 true ,类似地
I think you have at least a couple of options here. It's extra work but worth it.
You can encapsulate the string in a reference type. Since reference types are null if not present, that lets you know right away if a string was present or not (because the encapsulating reference type would be either non-null or null, if the string is non-empty or not.)
A final option you have is to add an extra complementary variable (perhaps a boolean) that is set on OnDeserializing/OnDeserialized/OnSerializing/OnSerialized and use this to track whether or not something was actually present on the wire. You might, for example, set this complementary variable to true only when you're actually serializing out a non-empty string and similarly