How to convert properly an array in json?

后端 未结 1 484
囚心锁ツ
囚心锁ツ 2021-01-24 01:33

I\'m a bit rusty with vb.net and I need your help for encoding this:

{\"monday\":{\"start\":\"09:00\",\"end\":\"18:00\",\"breaks\":[{\"start\":\"11:20\",\"end\":         


        
相关标签:
1条回答
  • 2021-01-24 02:24

    end would be an illegal property name in VB, break might choke C#. So this uses JSON.NET which allows you to change property names easily:

    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
    

    Deserialize to a Dictionary where the weekday names are the keys:

    Dim jstr = ...from whereever
    
    Dim result = JsonConvert.DeserializeObject(Of Dictionary(Of String, WorkDay))(jstr)
    

    To iterate:

    For Each kvp As KeyValuePair(Of String, WorkDay) In result
        Console.WriteLine("Day: {0}  start: {1}  end: {2}",
                          kvp.Key, kvp.Value.starttime, kvp.Value.endtime)
    Next
    

    Output:

    Day: monday start: 09:00 end: 18:00
    Day: tuesday start: 09:00 end: 18:00
    Day: wednesday start: 09:00 end: 18:00

    etc they are all the same

    I actually thought also to create an object that has the whole week If you want a flat object, add this 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
    
        ' a ctor to initialize the workday objects when
        ' starting from VB:
        Public Sub New
            monday = New WorkDay
            tuesday = New WorkDay
            ' etc...
        End Sub
    End Class
    
    ' deserialize:
    Dim myWkWeek = JsonConvert.DeserializeObject(Of WorkWeek)(jstr)
    

    It seems a bit redundant to me, but could be simpler depending on what it is and how it is used.


    To create that json from the VB objects, just serialize it:

    Dim jstr = JsonConvert.SerializeObject(myWkWeek)
    
    0 讨论(0)
提交回复
热议问题