caras caras - 5 months ago 76
jQuery Question

Read Json string with Newtonsoft C#

I cannot read json string with c#. I getting error while reading.

Json file

{
"Invoice": {
"Description": "New",
"InvoiceTypeId": "3d166468-3923-11e6-9e7c-40e230cfb8ae",
"CustomerAccountsId": "TEST",
"InvoiceDate": "2016-06-27",
"PayableDate": "2016-06-27",
"Prefix": "A",
"Serial": "34222",
"tag": "TEST"
},
"InvoiceLine": [
{
"ValueId": "c41d3d85-3a1e-11e6-9e7c-40e230cfb8ae",
"Qantity": "3",
"UnitId": "a72e0dde-3953-11e6-9e7c-40e230cfb8ae",
"Price": "1.500,00",
"VatRateId": "18",
"LineVat": "810,00",
"LineTotal": "5.310,00",
"Vat": "00a239f1-3c3a-11e6-9e7c-40e230cfb8ae"
},
{
"ValueId": "fd11b236-3952-11e6-9e7c-40e230cfb8ae",
"Qantity": "5",
"UnitId": "a72e0dde-3953-11e6-9e7c-40e230cfb8ae",
"Price": "1.000,00",
"VatRateId": "18",
"LineVat": "900,00",
"LineTotal": "5.900,00",
"Vat": "00a239f1-3c3a-11e6-9e7c-40e230cfb8ae"
}
]
}


"Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1."

JArray jsonVal = JArray.Parse(jsonArr) as JArray;
dynamic vars = jsonVal;


But everything right, I do not see bugs.

Answer

Don't do this...you're parsing to an array when it's clearly a complex object.

Use a converter such as Visual Studio or json2csharp.com to create the appropriate target object structure:

public class Invoice
{
    public string Description { get; set; }
    public string InvoiceTypeId { get; set; }
    public string CustomerAccountsId { get; set; }
    public string InvoiceDate { get; set; }
    public string PayableDate { get; set; }
    public string Prefix { get; set; }
    public string Serial { get; set; }
    public string tag { get; set; }
}

public class InvoiceLine
{
    public string ValueId { get; set; }
    public string Qantity { get; set; }
    public string UnitId { get; set; }
    public string Price { get; set; }
    public string VatRateId { get; set; }
    public string LineVat { get; set; }
    public string LineTotal { get; set; }
    public string Vat { get; set; }
}

public class Invoices
{
    public Invoice Invoice { get; set; }
    public List<InvoiceLine> InvoiceLine { get; set; }
}

Then simply use the JsonConvert methods to deserialize.

var parsedJson = JsonConvert.DeserializeObject<Invoices>(json);