gpt4 book ai didi

vb.net - 如何迭代json?

转载 作者:行者123 更新时间:2023-12-02 08:58:00 25 4
gpt4 key购买 nike

我正在尝试反序列化从查询返回的 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

现在 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

我想做的是迭代返回的对象,它具有以下结构:

enter image description here

你如何看到我有工作日,所以我想访问每一天并获取作为休息或开始和结束时间的属性。我怎样才能做到这一点?实际上,foreach 需要迭代中的特定一天,而我不能每天都有 7 个循环。

最佳答案

您的 WorkWeek 对象是所有日子的平面对象。它不是一个集合,因此您无法迭代它。不过,您可以反序列化为字典形式:

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 应用程序。放在一起,否则可能会更容易。

关于vb.net - 如何迭代json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34268030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com