Сериализация вложенного JSON с объектами - PullRequest
0 голосов
/ 12 июля 2019

Мне нужно создать JSON, который будет выглядеть так, как показано ниже.

{
    "ShipmentId": "111888",
    "BizId": "MORRIS",
    "BizSalesOrder": null,
    "Status": "00",
    "OrderType": "S01",
    "OrderClass": "PACKSHIP",
    "ShipmentLines": [
      {
        "ShipmentId": "111888",
        "QtyOrdered": 30.00,
        "QtyRequired": 30.00,
        "QtyDueOut": 0.00,
        "SOLineId": 1.00,
        "Stage": "90"
      },
      {
        "ShipmentId": "111888",
        "QtyOrdered": 40.00,
        "QtyRequired": 40.00,
        "QtyDueOut": 0.00,
        "SOLineId": 2.00,
        "Stage": "90"
      },
      {
        "ShipmentId": "111888",
        "QtyOrdered": 10.00,
        "QtyRequired": 10.00,
        "QtyDueOut": 0.00,
        "SOLineId": 3.00,
        "Stage": "90"
      },
      {
        "ShipmentId": "111888",
        "QtyOrdered": 5.00,
        "QtyRequired": 5.00,
        "QtyDueOut": 0.00,
        "SOLineId": 4.00,
        "Stage": "90"
      }
    ],
    "ShipAddress": [
      {
        "Table": "SHH",
        "ShipmentId": "111888",
        "AddressId": "ADD1",
        "Name": "John Smith",
        "Line1": "20 Michelin Ave",
        "Line2": null,
        "City": "LONDON",
        "Postcode": "A99 9BC",
        "Country": "GB"
      }
    ],
    "ShipContacts": [],
    "ShipmentDespatch": []
  }

У меня есть классы от http://www.jsonutils.com/ (ниже), но я почти уверен, что ShipmentLines должен быть "списком (из ShipmentLine)", но это все еще довольно запутанно для меня ..

Public Class ShipmentLine
    Public Property ShipmentId As String
    Public Property QtyOrdered As Double
    Public Property QtyRequired As Double
    Public Property QtyDueOut As Double
    Public Property SOLineId As Double
    Public Property Stage As String
End Class

Public Class ShipAddress
    Public Property Table As String
    Public Property ShipmentId As String
    Public Property AddressId As String
    Public Property Name As String
    Public Property Line1 As String
    Public Property Line2 As Object
    Public Property City As String
    Public Property Postcode As String
    Public Property Country As String
End Class

Public Class Shipment
    Public Property ShipmentId As String
    Public Property BizId As String
    Public Property BizSalesOrder As Object
    Public Property Status As String
    Public Property OrderType As String
    Public Property OrderClass As String
    Public Property ShipmentLines As List(Of ShipmentLine)
    Public Property ShipAddress As List(Of ShipAddress)
    Public Property ShipContacts As Object()
    Public Property ShipmentDespatch As Object()
End Class

Я могу сделать 1-й уровень JSON (ниже), но у меня есть проблемы с вложенными (и) несколькими объектами в одном выпуске.

Я новичок в VB.NET иЛюбитель программирования (как вы можете видеть), поэтому были бы полезны четкие инструкции.

Все линии доставки находятся в Listview1 (слева направо от ShipmentId до стадии), поэтому я не совсем уверен, как их получитьи также сериализовать их из Listview1 в JSON.

Если вы могли бы написать для меня код о том, как его сериализовать, что я получил ниже, но это только первый уровень json, без вложенности ...

Пожалуйста, помогите, я много раз посещал форум StackOverflow и сейчас просто повторяю все сообщения и не могу их понять ...

Dim Ship As New Shipment

Ship.ShipmentId = TextBox1.Text
Ship.BizId = TextBox2.Text
Ship.Status = "00"
Ship.OrderType = TextBox3.Text
Ship.Type = TextBox4.Text
Ship.OrderClass = TextBox5.Text


Dim json As String = JsonConvert.SerializeObject(Ship).ToString

1 Ответ

0 голосов
/ 12 июля 2019

Это можно сделать несколькими способами, но я следовал тому, что вы сделали.

Вот что я сделал:

Imports Newtonsoft.Json

Public Class Form1

    Public Class Shipment
        Public Property ShipmentId As String
        Public Property BizId As String
        Public Property BizSalesOrder As Object
        Public Property Status As String
        Public Property OrderType As String
        Public Property OrderClass As String
        Public Property ShipmentLines As List(Of ShipmentLine)
        Public Property ShipAddress As ShipAddress
        Public Property ShipContacts As Object()
        Public Property ShipmentDespatch As Object()
    End Class

    Public Class ShipmentLine
        Public Property ShipmentId As String
        Public Property QtyOrdered As Double
        Public Property QtyRequired As Double
        Public Property QtyDueOut As Double
        Public Property SOLineId As Double
        Public Property Stage As String
    End Class

    Public Class ShipAddress
        Public Property Table As String
        Public Property ShipmentId As String
        Public Property AddressId As String
        Public Property Name As String
        Public Property Line1 As String
        Public Property Line2 As Object
        Public Property City As String
        Public Property Postcode As String
        Public Property Country As String
    End Class

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim NewShipment As New Shipment With {
            .ShipmentId = "111888",
            .BizId = "MORRIS",
            .BizSalesOrder = "null",
            .Status = "00",
            .OrderType = "S01",
            .OrderClass = "PACKSHIP"
        }
        Dim NewShipmentLines As New List(Of ShipmentLine)
        For x = 0 To 3
            Dim NewShipmentLine As New ShipmentLine
            NewShipmentLine.ShipmentId = "111888"
            NewShipmentLine.QtyOrdered = x
            NewShipmentLine.QtyDueOut = x
            NewShipmentLine.SOLineId = x
            NewShipmentLine.Stage = x
            NewShipmentLines.Add(NewShipmentLine)
        Next
        NewShipment.ShipmentLines = NewShipmentLines
        Dim NewShipAdress As New ShipAddress With {
            .Table = "SHH",
            .ShipmentId = "111888",
            .AddressId = "ADD1",
            .Name = "John Smith",
            .Line1 = "20 Michelin Ave",
            .Line2 = "null",
            .City = "LONDON",
            .Postcode = "A99 9BC",
            .Country = "GB"
        }
        NewShipment.ShipAddress = NewShipAdress
        NewShipment.ShipContacts = Nothing
        NewShipment.ShipmentDespatch = Nothing

        Dim ResultJSON As String = JsonConvert.SerializeObject(NewShipment).ToString
        Debug.Print(ResultJSON) '
    End Sub
End Class

И результат:

{
   "ShipmentId":"111888",
   "BizId":"MORRIS",
   "BizSalesOrder":"null",
   "Status":"00",
   "OrderType":"S01",
   "OrderClass":"PACKSHIP",
   "ShipmentLines":[
      {
         "ShipmentId":"111888",
         "QtyOrdered":0.0,
         "QtyRequired":0.0,
         "QtyDueOut":0.0,
         "SOLineId":0.0,
         "Stage":"0"
      },
      {
         "ShipmentId":"111888",
         "QtyOrdered":1.0,
         "QtyRequired":0.0,
         "QtyDueOut":1.0,
         "SOLineId":1.0,
         "Stage":"1"
      },
      {
         "ShipmentId":"111888",
         "QtyOrdered":2.0,
         "QtyRequired":0.0,
         "QtyDueOut":2.0,
         "SOLineId":2.0,
         "Stage":"2"
      },
      {
         "ShipmentId":"111888",
         "QtyOrdered":3.0,
         "QtyRequired":0.0,
         "QtyDueOut":3.0,
         "SOLineId":3.0,
         "Stage":"3"
      }
   ],
   "ShipAddress":{
      "Table":"SHH",
      "ShipmentId":"111888",
      "AddressId":"ADD1",
      "Name":"John Smith",
      "Line1":"20 Michelin Ave",
      "Line2":"null",
      "City":"LONDON",
      "Postcode":"A99 9BC",
      "Country":"GB"
   },
   "ShipContacts":null,
   "ShipmentDespatch":null
}

Очевидно, вам нужно будет адаптировать его, чтобы он работал на вас, но он работает.Извините, я ничего не комментировал, если у вас есть вопросы, задавайте.

...