Search code examples
jsonvb.netjson.net

Adding a new item to a list json using Visual Basic


so I'm building an app and I'm reading a JSON file so I can add a new reservation but after searching online I didn't find any way to add a new dict to a list using visual basic and Newtonsoft.JSON.

The json file:

{"reservations": [{"time": "07:00 pm", "tableId": "1", "clientName": "Antonio Goncalves", "status": "pending"}]}

Basically I want to add a new dictionary of values inside the reservations list.

The current function

Public Sub SetReservation(time As String, tableId As String, clientName As String, Optional status As String = "pending")
        Dim reservationFile As String = File.ReadAllText(reservationJsonFile)

        If Not String.IsNullOrEmpty(reservationFile) And Not String.IsNullOrWhiteSpace(reservationFile) Then
            Dim reservationJson = Linq.JObject.Parse(reservationFile)
            Dim newReservationObject = Linq.JObject.FromObject(New Dictionary(Of Object, Object) From {{"time", time}, {"tableId", tableId}, {"clientName", clientName}, {"status", status}})

            Trace.WriteLine(newReservationObject)
        End If
    End Sub

Solution

  • Creating Classes that represent your json makes working with the json a lot simpler. See the classes created to represent your json data and how it's would be utilized in your sub routine.

    'Root object representing the "reservations" key in the json file
    Public Class ReservationData
        Public Property Reservations As List(Of Reservation)
    End Class
    
    'Properties match the expected keys in the json file
    Public Class Reservation
        Public Property Time As String
        Public Property TableId As String
        Public Property ClientName As String
        Public Property Status As String
    End Class
    

    Comments included as additional explanations.

    Public Sub SetReservation(time As String, tableId As String, clientName As String, Optional status As String = "pending")
        Dim reservationFile As String = File.ReadAllText(reservationJsonFile)
    
        If Not String.IsNullOrWhiteSpace(reservationFile) Then
            'Convert the json string to a ReservationData object
            Dim reservationData = JsonConvert.DeserializeObject(Of ReservationData)(reservationFile)
            'Create a new Reservation
            Dim newReservation = New Reservation With {.Time = time, .TableId = tableId, .ClientName = clientName, .Status = status}
    
            'Access the Reservations list from reservationData and Add the new Reservation
            reservationData.Reservations.Add(newReservation)
    
            'Overwrite the file with the updated reservationData
            File.WriteAllText(reservationJsonFile, JsonConvert.SerializeObject(reservationData))
        End If
    End Sub