【发布时间】:2018-12-23 12:16:35
【问题描述】:
我希望能够下载 JSON 文件,添加到其中,然后将修改后的文件保存回 Web 服务器。 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"
}
}
}
在 MSDN 上的 thread 中有一种提示如何添加到现有 JSON 消息,但该示例是针对 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#)都非常感激。
【问题讨论】: