所以我正在構建一個應用程式,我正在閱讀一個 JSON 檔案,以便我可以添加一個新的預訂,但在網上搜索后,我沒有找到任何方法來添加一個新dict的list使用visual basic和Newtonsoft.JSON。
json檔案:
{"reservations": [{"time": "07:00 pm", "tableId": "1", "clientName": "Antonio Goncalves", "status": "pending"}]}
基本上我想在保留串列中添加一個新的值字典。
當前功能
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
uj5u.com熱心網友回復:
創建代表您的 json 的類使使用 json 變得更加簡單。查看為表示您的 json 資料而創建的類以及如何在您的子例程中使用它。
'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
評論包括作為附加解釋。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/367653.html
