DataMember 发出默认值

发布于 2024-11-04 17:06:25 字数 590 浏览 1 评论 0原文

我有一个 .Net Web 服务函数,可以接受一个字符串。

然后该函数会将该字符串序列化为 JSON,但我只想在它的值不是“”时序列化它。

我找到了这些说明:

http://msdn.microsoft.com/en-us/ library/aa347792.aspx

[DataContract]
public class MyClass
{
   [DataMember (EmitDefaultValue=false)]
   public string myValue = ""
}

不幸的是,我无法从序列化中隐藏 myValue,因为“”不是字符串的 .Net 默认值(这有多愚蠢!)

两个之一选项发生

  1. 在 Web 服务上有某种属性将“”设置为 null

  2. 在类上有一些条件

我更喜欢第一个,因为它使代码更干净,但意见会很棒。

谢谢

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

  1. On the web service have some kind of attribute that sets the "" to null

  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笔芯 2024-11-11 17:06:25

您可以使用 DefaultValueAttribute 类:

[DataContract]
public class MyClass
{
    [DataMember (EmitDefaultValue=false)]
    [DefaultValue("")]
    public string myValue = ""
}

You can explicitly set what the default value is (for the purposes of serialization) using the DefaultValueAttribute class:

[DataContract]
public class MyClass
{
    [DataMember (EmitDefaultValue=false)]
    [DefaultValue("")]
    public string myValue = ""
}
十雾 2024-11-11 17:06:25

我认为你在这里至少有几个选择。这是额外的工作,但值得。

  • 您可以将字符串封装在引用类型中。由于引用类型如果不存在则为 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文