【问题标题】:Is there a way to keep object members from serializing .NET nulls as "null" in my JSON object?有没有办法阻止对象成员在我的 JSON 对象中将 .NET 空值序列化为“空值”?
【发布时间】:2025-12-21 21:45:11
【问题描述】:

我正在使用 WebMethods 返回自定义类的数组。从 Jquery .ajax 调用返回数组时,它被序列化为 JSON 对象,以便在我的 ASP.NET 应用程序中与 Javascript 一起使用。我遇到的是,如果 Sale 类的任何成员为 null(Nothing),它会在 JSON 对象中序列化为“null”字符串。我真的希望它只显示一个空字符串。我知道我可以编写一个清理方法来将空值转换为空字符串,但我真的很想知道一种为此设置默认行为的方法,以便将空值转换为空字符串。

这是我所有代码的外观:

<WebMethod()> _
Public Function GetData(ByVal SaleType As String) As Sale()

    Return DataLayer.GetSalesByType(SaleType)

End Function

Class Sale

    Public Property Type as String

    Public Property InvoiceNumber as Staing

End Class

【问题讨论】:

  • 将 null 值转换为“null”字符串是需要的行为,因为 null 和“”之间的区别在很多方面都很重要。

标签: javascript jquery asp.net json serialization


【解决方案1】:

肯定是

If x Is Nothing Then # String.IsNullOrEmpty(x) Then
    Return ""
End If
Return x

解决这个问题?

【讨论】:

  • 来自我的问题:I am aware that I can write a clean-up method to turn nulls into empty strings