我正在尝试反序列化从查询返回的json。基本上我的json有这样的结构:
{"monday":{"start":"13:21","end":"13:21","breaks":[{"start":"13:21","end":"13:21"},{"start":"13:21","end":"13:21"}]},"tuesday":{"start":null,"end":null,"breaks":[]},"wednesday":{"start":"13:21","end":"13:21","breaks":[{"start":"13:21","end":"13:21"}]},"thursday":{"start":null,"end":null,"breaks":[]},"friday":{"start":null,"end":null,"breaks":[]},"saturday":{"start":null,"end":null,"breaks":[]},"sunday":{"start":"13:21","end":"13:21","breaks":[{"start":"13:21","end":"13:21"},{"start":"13:21","end":"13:21"},{"start":"13:21","end":"13:21"}]}}
现在反序列化json我使用Newtonsoft.Json
库.Net
我将json传递给此函数作为参数:
Sub Working_Plan_Deserialize(ByVal wp As String)
Dim working_plan = JsonConvert.DeserializeObject(Of WorkWeek)(wp)
End Sub
我得到了这个结果:
Razor.Users +工作周
现在WorkWeek
类声明如下:
Public Class WorkDay
<JsonProperty("start")>
Public Property starttime As String
<JsonProperty("end")>
Public Property endtime As String
Public Property breaks As New List(Of Break)
End Class
Public Class Break
<JsonProperty("start")>
Public Property starttime As String
<JsonProperty("end")>
Public Property endtime As String
End Class
Public Class WorkWeek
Public Property monday As WorkDay
Public Property tuesday As WorkDay
Public Property wednesday As WorkDay
Public Property thursday As WorkDay
Public Property friday As WorkDay
Public Property saturday As WorkDay
Public Property sunday As WorkDay
Public Sub New()
monday = New WorkDay
tuesday = New WorkDay
wednesday = New WorkDay
thursday = New WorkDay
friday = New WorkDay
saturday = New WorkDay
sunday = New WorkDay
End Sub
End Class
我要做的是迭代返回的对象,它具有以下结构:
你如何看待我的工作日,所以我希望每天都可以访问,并将房产作为休息或开始和结束时间。我怎么能做到这一点?实际上,每个人都需要迭代中的特定日期,而且我每天都不能有7个循环。
答案 0 :(得分:3)
你的WorkWeek
物体是所有日子里的扁平物体。 不是一个集合,所以你不能迭代它。您可以反序列化为Dictionary表单:
Dim result = JsonConvert.DeserializeObject(Of Dictionary(Of String, WorkDay))(jstr)
但是,字典的顺序是未指定的,所以要按顺序迭代,你需要这样的东西:
Private DayNames As String() = {"sunday", "monday"...}
然后迭代字典:
For Each day As String in DayNames
Dim thisDay = result(day)
thisDay
将是指定日期的WorkDay
个对象。
最后,调试显示的信息量不大,但报告的内容并不多。如果单击箭头,则应显示每个WorkDay
对象的数据。您可以覆盖ToString()
,但在这些WorkDay对象中没有任何独特的报告:他们甚至不知道他们的日期。
其中一些是由于您从一个非常特定的json布局开始并从中驱动VB应用程序的事实。放在一起,否则可能会更容易。
答案 1 :(得分:0)
您的工作日是WorkWeek的个人财产。你不能迭代这样的那些。你从我看到的内容中有几个选择。
1)您可以在工作周内将工作日存储在列表(或其他一些集合)中,然后您可以按需要迭代它们。
2)你必须单独检查每个属性,并在循环中做你想做的事情