简体   繁体   中英

Adding to a JSON message in .NET

I want to be able to download a JSON file, add to it, and then save the amended file back to the web server. JSON file looks like this:

  {
  "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"
        }
    }
}

There was a sort of a hint how to add to an existing JSON message in this thread on MSDN, but the example is for a JSON message where the structure is much simpler than mine. In the example below, I want to add another car to the JSON message. I can amend an existing car, and create a new object with a new car in it (sort of) but no idea how to merge the results back into my existing 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

I'm using the .NET JavaScriptSerializer. I've looked at the code samples in JSON.net in case there was anything there that I could/should use instead, but couldn't really see anything.

Any help, or pointing me in the right direction, (VB or C#) gratefully received.

If you're just adding one item, instead of creating a separate list you can just Resize or ReDim Preserve your existing array:

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)

Then add a new car to the empty array slot:

CarObject.vehicles.car.example(CarObject.vehicles.car.example.Length - 1) = New Example With {
    .make = "Bugatti",
    .model = "Veyron"
}

If you do need to add more than one item at a time, again resize the array and have a For -loop put the items from the list into the array instead:

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)

Then loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM