【发布时间】:2020-11-18 13:52:48
【问题描述】:
我目前正在使用存储在数据表中的数据构建 JSON。但是,发生的情况是数据表的列中不存在数据,它向我的属性返回一个空 ("") 字符串。
这会出现在我的 JSON 上,然后由于相关 Web 服务未对其进行验证而无法提取。
但是,如果我将值设置为“Nothing”,它不会序列化,因此不会出现在 JSON 中。我怎样才能让 Nothing 返回到 string = "" 的所有字符串值。
我可以通过编写一个测试字符串并返回 Nothing 的函数来做到这一点,但是我觉得我必须这样做一定有问题。
这是一个例子
Public Class Policy
<JsonProperty("policy_id", NullValueHandling:=NullValueHandling.Ignore)>
Public Property policy_id As String = Nothing
<JsonProperty("insurer_name", NullValueHandling:=NullValueHandling.Ignore)>
Public Property insurer_name As String = Nothing
<JsonProperty("policy_name", NullValueHandling:=NullValueHandling.Ignore)>
Public Property policy_name As String = Nothing
<JsonProperty("product_name", NullValueHandling:=NullValueHandling.Ignore)>
Public Property product_name As String = Nothing
<JsonProperty("sale_date", NullValueHandling:=NullValueHandling.Ignore)>
Public Property sale_date As DateTime = Nothing
<JsonProperty("start_date", NullValueHandling:=NullValueHandling.Ignore)>
Public Property start_date As DateTime = Nothing
<JsonProperty("end_date", NullValueHandling:=NullValueHandling.Ignore)>
Public Property end_date As DateTime = Nothing
<JsonProperty("status", NullValueHandling:=NullValueHandling.Ignore)>
Public Property status As String = Nothing
<JsonProperty("vehicles", NullValueHandling:=NullValueHandling.Ignore)>
Public Property vehicles As New List(Of Vehicle)
<JsonProperty("people", NullValueHandling:=NullValueHandling.Ignore)>
Public Property persons As New List(Of Person)
End Class
Private Function get_JSON(ByVal branch As String, ByVal policyref As String) As String
For Each p As DataRow In dt_policies.Rows
Dim oPolicy As New Policy() With {
.policy_id = p("B@") & p("PolRef@"),
.insurer_name = p("insurer_name"),
.policy_name = p("policy_name"),
.product_name = p("product_name"),
.sale_date = p("sale_date"),
.start_date = p("start_date"),
.end_date = p("end_date"),
.status = p("status"),
.vehicles = get_vehicles(p("B@"), p("PolRef@")),
.persons = get_persons(p("B@"), p("PolRef@"))
}
Dim json As String = JsonConvert.SerializeObject(oPolicy, NullValueHandling.Ignore)
Return json
Next
End Function
Private Function ReturnNothing(ByVal rstring As String) As String
If rstring = "" Then
Return Nothing
Else
Return rstring
End If
End Function
【问题讨论】:
-
@AndrewMorton - 问题是 DataTable 的返回是 DBNull 或空字符串......所以这会覆盖“默认值”。 DBNull 导致失败,Empty String 表示元素已显示,我已经提出了我创建的解决方法,但显然有更好的方法。
-
您可以将其称为数据规范化,而不是将其称为解决方法。
-
我不相信这是正确的做法。