Avatar of Peter Nordberg
Peter NordbergFlag for Sweden

asked on 

Deserialize json with in vb

I have a json string looking like this:
{
    "MetaInformation": {
        "@TotalResources": 170,
        "@TotalPages": 85,
        "@CurrentPage": 1
    },
    "Invoices": [
        {
            "@url": "https://api.se/3/invoices/1",
            "Balance": 2069,
            "Booked": false,
            "Cancelled": false,
            "CostCenter": "",
            "Currency": "SEK",
            "CurrencyRate": "1",
            "CurrencyUnit": 1,
            "CustomerName": " Company A ",
            "CustomerNumber": "12224",
            "DocumentNumber": "1",
            "DueDate": "2016-09-04",
            "ExternalInvoiceReference1": "",
            "ExternalInvoiceReference2": "",
            "InvoiceDate": "2016-08-05",
            "InvoiceType": "INVOICE",
            "NoxFinans": false,
            "OCR": "133",
            "VoucherNumber": null,
            "VoucherSeries": null,
            "VoucherYear": null,
            "WayOfDelivery": "",
            "TermsOfPayment": "30",
            "Project": "",
            "Sent": true,
            "Total": 2069,
            "FinalPayDate": null
        },
        {
            "@url": "https://api.se/3/invoices/2",
            "Balance": 6250,
            "Booked": false,
            "Cancelled": false,
            "CostCenter": "",
            "Currency": "SEK",
            "CurrencyRate": "1",
            "CurrencyUnit": 1,
            "CustomerName": " Company B ",
            "CustomerNumber": "12224",
            "DocumentNumber": "2",
            "DueDate": "2016-09-14",
            "ExternalInvoiceReference1": "",
            "ExternalInvoiceReference2": "",
            "InvoiceDate": "2016-08-15",
            "InvoiceType": "INVOICE",
            "NoxFinans": false,
            "OCR": "232",
            "VoucherNumber": null,
            "VoucherSeries": null,
            "VoucherYear": null,
            "WayOfDelivery": "",
            "TermsOfPayment": "30",
            "Project": "",
            "Sent": true,
            "Total": 6250,
            "FinalPayDate": null
        }
    ]
}

Open in new window

I want to deserialize it and have tried this:
 Dim json As String = FNApiRequests.FNGetRequest("invoices/", "GET")
        Dim invoices As List(Of Invoice) = JsonConvert.DeserializeObject(Of List(Of Invoice))(json)

Open in new window

The class model looks like this:
Public Class FNInvoiceModel
    Public Property Invoice As Invoice
End Class

Public Class Invoice
    Public Property url As String
    Public Property urlTaxReductionList As String
    Public Property AdministrationFee As Integer
    Public Property AdministrationFeeVAT As Integer
    Public Property Address1 As String
    Public Property Address2 As String
    Public Property Balance As Integer
    Public Property BasisTaxReduction As Integer
    Public Property Booked As Boolean
    Public Property Cancelled As Boolean
    Public Property City As String
    Public Property Comments As String
    Public Property ContractReference As Integer
    Public Property ContributionPercent As Integer
    Public Property ContributionValue As Integer
    Public Property Country As String
    Public Property CostCenter As String
    Public Property Credit As String
    Public Property CreditInvoiceReference As String
    Public Property Currency As String
    Public Property CurrencyRate As Integer
    Public Property CurrencyUnit As Integer
    Public Property CustomerName As String
    Public Property CustomerNumber As String
    Public Property DeliveryAddress1 As String
    Public Property DeliveryAddress2 As String
    Public Property DeliveryCity As String
    Public Property DeliveryCountry As String
    Public Property DeliveryDate As String
    Public Property DeliveryName As String
    Public Property DeliveryZipCode As String
    Public Property DocumentNumber As String
    Public Property DueDate As String
    Public Property EDIInformation As Ediinformation
    Public Property EmailInformation As Emailinformation
    Public Property EUQuarterlyReport As Boolean
    Public Property ExternalInvoiceReference1 As String
    Public Property ExternalInvoiceReference2 As String
    Public Property Freight As Integer
    Public Property FreightVAT As Integer
    Public Property Gross As Integer
    Public Property HouseWork As Boolean
    Public Property InvoiceDate As String
    Public Property InvoicePeriodStart As String
    Public Property InvoicePeriodEnd As String
    Public Property InvoicePeriodReference As String
    Public Property InvoiceRows As List(Of Invoicerow)
    Public Property InvoiceType As String
    Public Property Labels() As Label
    Public Property Language As String
    Public Property LastRemindDate As String
    Public Property Net As Integer
    Public Property NotCompleted As Boolean
    Public Property NoxFinans As Boolean
    Public Property OCR As String
    Public Property OfferReference As String
    Public Property OrderReference As String
    Public Property OrganisationNumber As String
    Public Property OurReference As String
    Public Property PaymentWay As String
    Public Property Phone1 As String
    Public Property Phone2 As String
    Public Property PriceList As String
    Public Property PrintTemplate As String
    Public Property Project As String
    Public Property WareHouseReady As Boolean
    Public Property OutboundDate As String
    Public Property Remarks As String
    Public Property Reminders As Integer
    Public Property RoundOff As Integer
    Public Property Sent As Boolean
    Public Property TaxReduction As Integer
    Public Property TermsOfDelivery As String
    Public Property TermsOfPayment As String
    Public Property TimeBasisReference As Integer
    Public Property Total As Integer
    Public Property TotalToPay As Integer
    Public Property TotalVAT As Integer
    Public Property VATIncluded As Boolean
    Public Property VoucherNumber As Integer
    Public Property VoucherSeries As String
    Public Property VoucherYear As Integer
    Public Property WayOfDelivery As String
    Public Property YourOrderNumber As String
    Public Property YourReference As String
    Public Property ZipCode As String
    Public Property AccountingMethod As String
    Public Property TaxReductionType As String
    Public Property FinalPayDate As String
End Class

Public Class Ediinformation
    Public Property EDIGlobalLocationNumber As String
    Public Property EDIGlobalLocationNumberDelivery As String
    Public Property EDIInvoiceExtra1 As String
    Public Property EDIInvoiceExtra2 As String
    Public Property EDIOurElectronicReference As String
    Public Property EDIYourElectronicReference As String
    Public Property EDIStatus As String
End Class

Public Class Emailinformation
    Public Property EmailAddressFrom As String
    Public Property EmailAddressTo As String
    Public Property EmailAddressCC As String
    Public Property EmailAddressBCC As String
    Public Property EmailSubject As String
    Public Property EmailBody As String
End Class

Public Class Invoicerow
    Public Property AccountNumber As Integer
    Public Property ArticleNumber As String
    Public Property ContributionPercent As String
    Public Property ContributionValue As String
    Public Property CostCenter As String
    Public Property DeliveredQuantity As String
    Public Property Description As String
    Public Property Discount As Integer
    Public Property DiscountType As String
    Public Property HouseWork As Boolean
    Public Property HouseWorkHoursToReport As Integer
    Public Property HouseWorkType As String
    Public Property Price As Integer
    Public Property PriceExcludingVAT As Integer
    Public Property Project As String
    Public Property StockPointCode As String
    Public Property Total As Integer
    Public Property TotalExcludingVAT As Integer
    Public Property Unit As String
    Public Property VAT As Integer
End Class

Public Class Label
    Public Property Id As Integer
End Class


Open in new window

But I get this error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Invoice]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Open in new window

How can I deserialize the string in a correct way?

Thanks for help!
ASP.NETVisual Basic.NET.NET ProgrammingJSON

Avatar of undefined
Last Comment
Jonathan D.
Avatar of David Favor
David Favor
Flag of United States of America image

At first glance...

1) Your JSON is valid, per the tester I just used.

https://jsonformatter.curiousconcept.com/

2) Your JSON produces a hierarchical structure, with 2x arrays.

3) Your class is flat... scalarish... no way to have this type of data directly deserialize into your class.

4) It appears what's required in your case is to parse the JSON, then iterate over each invoice row, create in instance of your InvoiceRow class.

5) Likely better to retire InvoiceRow, creating an instance of your Invoice class instead.

6) Said differently, there's a mismatch between your JSON data + classes, so there's no way to directly deserialize into a set of nested objects in a single call, iteration will be an easy fix, where code will also be more understandable to anyone looking at this code in the future.
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Jonathan D.
Jonathan D.
Flag of Israel image

Go here and paste the json you added to your post to generate the models in VB.net, after that install a nuget called json.net and then use this method to deserialize the json into the generic typed object.
.NET Programming
.NET Programming

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

137K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo