Я хочу иметь возможность загрузить файл JSON, добавить к нему, а затем сохранить измененный файл обратно на веб-сервер. Файл JSON выглядит так:
{
"vehicles": {
"motorbike": {
"example": [{
"make": "Kawasaki",
"model": "Z1"
},
{
"make": "Honda",
"model": "Goldwing"
}
],
"description": "Usually 2 wheels, with no roof"
},
"car": {
"example": [{
"make": "Skoda",
"model": "Fabia"
}],
"description": "Usually 4 wheels, with at least 4 seats and roof"
},
"lorry": {
"example": [{
"make": "Mack",
"model": "Anthem"
}],
"description": "Usually lots of wheels, with a roof, and a loud horn"
}
}
}
Был своего рода намек на то, как добавить к существующему сообщению JSON в этом нить на MSDN, но пример для сообщения JSON, структура которого намного проще, чем у меня. В приведенном ниже примере я хочу добавить еще одну машину в сообщение JSON. Я могу изменить существующий автомобиль и создать новый объект с новым автомобилем в нем (вроде), но я не знаю, как объединить результаты обратно в мой существующий JSON:
Imports System.Web.Script.Serialization
Public Class Example
Public Property make As String
Public Property model As String
End Class
Public Class Motorbike
Public Property example As Example()
Public Property description As String
End Class
Public Class Car
Public Property example As Example()
Public Property description As String
End Class
Public Class Lorry
Public Property example As Example()
Public Property description As String
End Class
Public Class Vehicles
Public Property motorbike As Motorbike
Public Property car As Car
Public Property lorry As Lorry
End Class
Public Class VehicleRoot
Public Property vehicles As Vehicles
End Class
Dim contents As String
'Deserialise the JSON
Using streamReader As StreamReader = New StreamReader("C:\Users\idiot\Desktop\example.json")
'Get entire contents of file in string.
contents = streamReader.ReadToEnd()
End Using
Dim CarObject As VehicleRoot = New JavaScriptSerializer().Deserialize(Of VehicleRoot)(contents)
'Can amend existing JSON, but how to add?
CarObject.vehicles.car.example(0).model = "Octavia"
Dim newData As New List(Of Example)
With newData
.Add(New Example With {.make = "Bugatti", .model = "Veyron"})
End With
Dim p As New Car With {.example = newData.ToArray}
'I'm stuck now.
'CarObject.vehicles.concat
'Reserialise the amended JSON
Dim serializer = New JavaScriptSerializer()
Dim serializedResult = serializer.Serialize(p)
Using writer As StreamWriter =
New StreamWriter("C:\Users\idiot\Desktop\example_v2.json")
writer.Write(serializedResult)
End Using
Я использую .NET JavaScriptSerializer. Я просмотрел образцы кода в JSON.net на случай, если там есть что-то, что я мог бы / должен использовать вместо этого, но ничего не увидел.
Любая помощь или указание в правильном направлении (VB или C#) с благодарностью получены.





Если вы просто добавляете один элемент, вместо создания отдельного списка вы можете просто Resize или ReDim Preserve существующего массива:
Array.Resize:
Array.Resize(CarObject.vehicles.car.example, CarObject.vehicles.car.example.Length + 1)
ReDim Preserve:
ReDim Preserve CarObject.vehicles.car.example(CarObject.vehicles.car.example.Length)
Затем добавьте новую машину в пустой слот массива:
CarObject.vehicles.car.example(CarObject.vehicles.car.example.Length - 1) = New Example With {
.make = "Bugatti",
.model = "Veyron"
}
Если вам действительно нужно добавить более одного элемента за раз, снова измените размер массива и попросите цикл For вместо этого поместить элементы из списка в массив:
Dim newData As New List(Of Example)
With newData
.Add(New Example With {.make = "Bugatti", .model = "Veyron"})
.Add(New Example With {.make = "Ford", .model = "Focus"})
End With
Array.Resize:
Array.Resize(CarObject.vehicles.car.example, CarObject.vehicles.car.example.Length + newData.Count)
ReDim Preserve:
ReDim Preserve CarObject.vehicles.car.example(CarObject.vehicles.car.example.Length + newData.Count - 1)
Затем цикл:
For i = 0 To newData.Count - 1
Dim j As Integer = CarObject.vehicles.car.example.Length - newData.Count + i
CarObject.vehicles.car.example(j) = newData(i)
Next
@basinbasin: Рад, что смог помочь! Бог Jul och Gott Nytt År! ;)
Прекрасно работает! Большое спасибо! Боже Джул!