Json-Objekt zerlegen und durchlaufen

  • VB.NET

Es gibt 11 Antworten in diesem Thema. Der letzte Beitrag () ist von Majomi.

    Json-Objekt zerlegen und durchlaufen

    Hallo,

    ich habe zum ersten mal mit Json zu tun und komme hier ziemlich in's Schleudern.
    Ich habe ein komplexes Json, das mehrere Unterebenen hat, die ziemlich verschachtelt sind.
    Ich kann bislang nur die obererste Ebene auslesen. Das mache ich mit folgendem Code, den ich online gefunden habe:

    VB.NET-Quellcode

    1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    2. Dim json As String = File.ReadAllText("json.txt")
    3. ' Dim json As String = "{"id": "100001363520746", "name": "Jenni Hapunkt", "first_name": "Jenni", "last_name": "Hapunkt", "gender": "female","locale": "de_DE" }"
    4. ' javascript serialisierer
    5. Dim jsonSerializer As New System.Web.Script.Serialization.JavaScriptSerializer
    6. ' generisch zu json dictionary konvertieren
    7. Dim dict1 As Dictionary(Of String, Object) = jsonSerializer.Deserialize(Of Dictionary(Of String, Object))(json)
    8. ' oder standardmässig über deserializeobject + casten
    9. ' Dim o As Object = jsonSerializer.DeserializeObject(json)
    10. ' Dim dict2 As Dictionary(Of String, Object) = DirectCast(o, Dictionary(Of String, Object))
    11. ' ansprechen kann man es jetzt einfach
    12. MessageBox.Show(CStr(dict1("Timestamp"))) ' die objekte im dict müssen noch richtig gecastet werden
    13. End Sub


    Allerdings begreife ich nicht, wie ich den auf die nächste höheren Ebenen springen kann.

    Mein Json sieht so aus:

    {"Timestamp":"2017-03-07T15:45:50.000Z","Ack":"Success","Version":"967","Build":"E967_INTL_APISELLING_17965958_R1","SaleRecord":[{"SellingManagerSoldTransaction":[{"TransactionID":1361189289020,"SaleRecordID":3185,"ItemID":"302210133391","QuantitySold":1,"ItemTitle":"Testartikel ","ListingType":"StoresFixedPrice","Relisted":false,"SecondChanceOfferSent":false,"CustomLabel":"ZY006","SoldOn":"eBay","ListedOn":["eBay"],"CharityListing":false,"OrderLineItemID":"3022-136"}],"ShippingAddress":{"Name":"Frau XY","PostalCode":"12345"},"ShippingDetails":{"ShippingType":"Flat"},"TotalAmount":{"value":233.95,"currencyID":"EUR"},"TotalQuantity":1,"ActualShippingCost":{"value":0,"currencyID":"EUR"},"OrderStatus":{"CheckoutStatus":"CheckoutComplete","PaidStatus":"Paid","ShippedStatus":"Unshipped","PaymentMethodUsed":"PayPal","FeedbackSent":false,"TotalEmailsSent":1,"PaidTime":"2017-03-07T14:28:48.000Z"},"SalePrice":{"value":233.95,"currencyID":"EUR"},"DaysSinceSale":0,"BuyerID":"katjuscha-blau","BuyerEmail":"xxx@web.de","SaleRecordID":3185,"CreationTime":"2017-03-07T14:27:15.000Z"}],"PaginationResult":{"TotalNumberOfPages":1,"TotalNumberOfEntries":13}}
    Mach dir ne Klasse aus dem Json z.B mit jsonutils.com/ ->
    Spoiler anzeigen

    VB.NET-Quellcode

    1. Public Class SellingManagerSoldTransaction
    2. Public Property TransactionID As Long
    3. Public Property SaleRecordID As Integer
    4. Public Property ItemID As String
    5. Public Property QuantitySold As Integer
    6. Public Property ItemTitle As String
    7. Public Property ListingType As String
    8. Public Property Relisted As Boolean
    9. Public Property SecondChanceOfferSent As Boolean
    10. Public Property CustomLabel As String
    11. Public Property SoldOn As String
    12. Public Property ListedOn As String()
    13. Public Property CharityListing As Boolean
    14. Public Property OrderLineItemID As String
    15. End Class
    16. Public Class ShippingAddress
    17. Public Property Name As String
    18. Public Property PostalCode As String
    19. End Class
    20. Public Class ShippingDetails
    21. Public Property ShippingType As String
    22. End Class
    23. Public Class TotalAmount
    24. Public Property value As Double
    25. Public Property currencyID As String
    26. End Class
    27. Public Class ActualShippingCost
    28. Public Property value As Integer
    29. Public Property currencyID As String
    30. End Class
    31. Public Class OrderStatus
    32. Public Property CheckoutStatus As String
    33. Public Property PaidStatus As String
    34. Public Property ShippedStatus As String
    35. Public Property PaymentMethodUsed As String
    36. Public Property FeedbackSent As Boolean
    37. Public Property TotalEmailsSent As Integer
    38. Public Property PaidTime As DateTime
    39. End Class
    40. Public Class SalePrice
    41. Public Property value As Double
    42. Public Property currencyID As String
    43. End Class
    44. Public Class SaleRecord
    45. Public Property SellingManagerSoldTransaction As SellingManagerSoldTransaction()
    46. Public Property ShippingAddress As ShippingAddress
    47. Public Property ShippingDetails As ShippingDetails
    48. Public Property TotalAmount As TotalAmount
    49. Public Property TotalQuantity As Integer
    50. Public Property ActualShippingCost As ActualShippingCost
    51. Public Property OrderStatus As OrderStatus
    52. Public Property SalePrice As SalePrice
    53. Public Property DaysSinceSale As Integer
    54. Public Property BuyerID As String
    55. Public Property BuyerEmail As String
    56. Public Property SaleRecordID As Integer
    57. Public Property CreationTime As DateTime
    58. End Class
    59. Public Class PaginationResult
    60. Public Property TotalNumberOfPages As Integer
    61. Public Property TotalNumberOfEntries As Integer
    62. End Class
    63. Public Class JsonClass
    64. Public Property Timestamp As DateTime
    65. Public Property Ack As String
    66. Public Property Version As String
    67. Public Property Build As String
    68. Public Property SaleRecord As SaleRecord()
    69. Public Property PaginationResult As PaginationResult
    70. End Class


    Und dann de-serialisiere in diese Klasse auch würde ich dir empfehlen json.net zu benutzen:

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „Majomi“ ()

    Moin!

    Ein Objekt befüllen (die settings sind nicht zwingend notwendig, kann man auch weglassen)

    VB.NET-Quellcode

    1. dim result=JsonConvert.DeserializeObject(Of DEINEKLASSE)(Tag, New JsonSerializerSettings() With {.DefaultValueHandling = DefaultValueHandling.Ignore})


    oder das:

    VB.NET-Quellcode

    1. JsonConvert.PopulateObject(JSONDataStructureSource, DEINEKLASSE)


    Einen String aus einem Objekt machen:

    VB.NET-Quellcode

    1. dim result as string=JsonConvert.SerializeObject(DEINEKLASSE)


    Alles weitere steht in der Newtonsoft onlinehilfe
    Der Beitrag wurde aus 100% wiederverwendbaren Elektronen erstellt!
    Außerdem: Bitte künftig solche JSON Objekte richtig formatiert entweder in <code> Tags oder in <spoiler><code> Tags einfügen :D
    Spoiler anzeigen

    Quellcode

    1. {
    2. "Timestamp":"2017-03-07T15:45:50.000Z",
    3. "Ack":"Success",
    4. "Version":"967",
    5. "Build":"E967_INTL_APISELLING_17965958_R1",
    6. "SaleRecord":[
    7. {
    8. "SellingManagerSoldTransaction":[
    9. {
    10. "TransactionID":1361189289020,
    11. "SaleRecordID":3185,
    12. "ItemID":"302210133391",
    13. "QuantitySold":1,
    14. "ItemTitle":"Testartikel ",
    15. "ListingType":"StoresFixedPrice",
    16. "Relisted":false,
    17. "SecondChanceOfferSent":false,
    18. "CustomLabel":"ZY006",
    19. "SoldOn":"eBay",
    20. "ListedOn":[
    21. "eBay"
    22. ],
    23. "CharityListing":false,
    24. "OrderLineItemID":"3022-136"
    25. }
    26. ],
    27. "ShippingAddress":{
    28. "Name":"Frau XY",
    29. "PostalCode":"12345"
    30. },
    31. "ShippingDetails":{
    32. "ShippingType":"Flat"
    33. },
    34. "TotalAmount":{
    35. "value":233.95,
    36. "currencyID":"EUR"
    37. },
    38. "TotalQuantity":1,
    39. "ActualShippingCost":{
    40. "value":0,
    41. "currencyID":"EUR"
    42. },
    43. "OrderStatus":{
    44. "CheckoutStatus":"CheckoutComplete",
    45. "PaidStatus":"Paid",
    46. "ShippedStatus":"Unshipped",
    47. "PaymentMethodUsed":"PayPal",
    48. "FeedbackSent":false,
    49. "TotalEmailsSent":1,
    50. "PaidTime":"2017-03-07T14:28:48.000Z"
    51. },
    52. "SalePrice":{
    53. "value":233.95,
    54. "currencyID":"EUR"
    55. },
    56. "DaysSinceSale":0,
    57. "BuyerID":"katjuscha-blau",
    58. "BuyerEmail":"xxx@web.de",
    59. "SaleRecordID":3185,
    60. "CreationTime":"2017-03-07T14:27:15.000Z"
    61. }
    62. ],
    63. "PaginationResult":{
    64. "TotalNumberOfPages":1,
    65. "TotalNumberOfEntries":13
    66. }
    67. }

    In general (across programming languages), a pointer is a number that represents a physical location in memory. A nullpointer is (almost always) one that points to 0, and is widely recognized as "not pointing to anything". Since systems have different amounts of supported memory, it doesn't always take the same number of bytes to hold that number, so we call a "native size integer" one that can hold a pointer on any particular system. - Sam Harwell
    Mit deinem Beispiel
    dim result=JsonConvert.DeserializeObject(Of DEINEKLASSE)(Tag, New JsonSerializerSettings() With {.DefaultValueHandling = DefaultValueHandling.Ignore})
    bekomme ich das nun wohl in unten gezeigte Klasse deserialisiert.... (die ich mit den Json Utils generiert habe)

    und nun? Sorry, ich habe in VB.net noch nie mit Klassen gearbeitet. Das ist mir 3 Level zu hoch :(

    Die Variable Result kann ich leider nicht ansprechen.


    VB.NET-Quellcode

    1. Public Class NameValueList
    2. Public Property Name As String
    3. Public Property Value As String()
    4. End Class
    5. Public Class VariationSpecific
    6. Public Property NameValueList As NameValueList()
    7. End Class
    8. Public Class Variation
    9. Public Property VariationSpecifics As VariationSpecific()
    10. End Class
    11. Public Class SellingManagerSoldTransaction
    12. Public Property TransactionID As Object
    13. Public Property SaleRecordID As Integer
    14. Public Property ItemID As String
    15. Public Property QuantitySold As Integer
    16. Public Property ItemTitle As String
    17. Public Property ListingType As String
    18. Public Property Relisted As Boolean
    19. Public Property SecondChanceOfferSent As Boolean
    20. Public Property CustomLabel As String
    21. Public Property SoldOn As String
    22. Public Property ListedOn As String()
    23. Public Property CharityListing As Boolean
    24. Public Property OrderLineItemID As String
    25. Public Property Variation As Variation
    26. End Class
    27. Public Class ShippingAddress
    28. Public Property Name As String
    29. Public Property PostalCode As String
    30. End Class
    31. Public Class ShippingDetails
    32. Public Property ShippingType As String
    33. End Class
    34. Public Class TotalAmount
    35. Public Property value As Double
    36. Public Property currencyID As String
    37. End Class
    38. Public Class ActualShippingCost
    39. Public Property value As Integer
    40. Public Property currencyID As String
    41. End Class
    42. Public Class OrderStatus
    43. Public Property CheckoutStatus As String
    44. Public Property PaidStatus As String
    45. Public Property ShippedStatus As String
    46. Public Property PaymentMethodUsed As String
    47. Public Property FeedbackSent As Boolean
    48. Public Property TotalEmailsSent As Integer
    49. Public Property PaidTime As DateTime
    50. Public Property FeedbackReceived As String
    51. End Class
    52. Public Class SalePrice
    53. Public Property value As Double
    54. Public Property currencyID As String
    55. End Class
    56. Public Class SaleRecord
    57. Public Property SellingManagerSoldTransaction As SellingManagerSoldTransaction()
    58. Public Property ShippingAddress As ShippingAddress
    59. Public Property ShippingDetails As ShippingDetails
    60. Public Property TotalAmount As TotalAmount
    61. Public Property TotalQuantity As Integer
    62. Public Property ActualShippingCost As ActualShippingCost
    63. Public Property OrderStatus As OrderStatus
    64. Public Property SalePrice As SalePrice
    65. Public Property DaysSinceSale As Integer
    66. Public Property BuyerID As String
    67. Public Property BuyerEmail As String
    68. Public Property SaleRecordID As Integer
    69. Public Property CreationTime As DateTime
    70. End Class
    71. Public Class PaginationResult
    72. Public Property TotalNumberOfPages As Integer
    73. Public Property TotalNumberOfEntries As Integer
    74. End Class
    75. Public Class Example
    76. Public Property Timestamp As DateTime
    77. Public Property Ack As String
    78. Public Property Version As String
    79. Public Property Build As String
    80. Public Property SaleRecord As SaleRecord()
    81. Public Property PaginationResult As PaginationResult
    82. End Class
    Das Json-Objekt soll eine Bestellung darstellen richtig?
    Dann solltest du die Klasse auch danach benennen: In dem Fall Public Class Example zum Beispiel : Public Class Order
    Dann kannst du es ganz einfach mit

    VB.NET-Quellcode

    1. Dim result = JsonConvert.DeserializeObject(Of Order)

    Dann solltest du mit result.Timestamp zum Beispiel auf den Timestamp zugreifen können!
    Genau das macht die Klasse eben nicht. Die automatisch generierte Klasse kennt (hab diese ja extra angehängt)
    nur Name und Value als Public Werte.
    Ich verstehe z.B. hier nicht, warum das nicht 1 große Klasse mit diversen Werten sondern eben mehrere Klassen sind. Von außen kann ich aber nur die erste ansprechen
    Steh aber nach wie vor auf der Leitung.

    Ich war der Meinung mit
    dim result=JsonConvert.DeserializeObject(Of NameValueList)(jsontext, New JsonSerializerSettings() With {.DefaultValueHandling = DefaultValueHandling.Ignore})
    bekommt die Variable Result die gesamte oben gezeigte Klasse zugewiesen und ich kann mich dann darin bewegen
    Nur hat result eben nur die Werte Name und Value.
    Wie also bekomme ich den nun einen Zugriff auf die Klasse Example?