Nested Json deserialize C #

I have a json line like this:

[
  {
    "ID": 123456789,
    "userInf": {
      "Name": "NameSurname1",
      "Adress": "example adress"
    },
    "price": "3898.30",
    "kdv": "701.69",
    "total": "4599,99",
    "note": "example note"
  },
  {
    "ID": 98756431,
    "userInf": {
      "Name": "NameSurname2",
      "Adress": "example address2"
    },
    "price": "1116.10",
    "kdv": "82.90",
    "total": "1199.00",
    "note": "example note2"
  }
]

And create the classes as follows:

public partial class Sale
{
    public long ID { get; set; }
    public UserInf UserInf { get; set; }
    public string Price { get; set; }
    public string Kdv { get; set; }
    public string Total { get; set; }
    public string note { get; set; }
}

public partial class UserInf
{
    public string Name { get; set; }
    public string Adress { get; set; }
}

And I call json with this code and deserialize;

var data = JsonConvert.DeserializeObject<Sale>(jsonstring);
var shapedData = Enumerable.Range(0, 1).Select(x =>
                    new
                    {
                        ID = data.ID,
                        userInf = data.UserInf.Name,
                        price = data.Price,
                        kdv = data.Kdv,
                        total = data.Total,
                        note= data.Note
                    }).ToList();

DataTable dt = ToDataTable(shapedData);
dataGridView1.DataSource = dt;

and I get an error. But if I change my json and cut out the second half and delete the character code [,], it just works fine. I need to deserialize a few, as mentioned above, and have tried several deserialization methods, but this is the closest way that I still get.

I get an error on this line;

var data = JsonConvert.DeserializeObject<Sale>(jsonstring);

Error

It is not possible to deserialize the current JSON array (for example, [1,2,3]) to type .. etc.

I know that I am missing something very simple, but I don’t have a coder friend to ask. I would appreciate if you would suggest a better way to do this.

+4
source share
2

;

JsonConvert.DeserializeObject<List<Sale>>(jsonstring);

linq :

var shapedData = data.Select(x =>
    new
    {
       ID = x.ID,
       userInf = x.UserInf.Name,
       price = x.Price,
       kdv = x.Kdv,
       total = x.Total,
       note = x.note
    }).ToList();
+4

, var, ,

List<Sale> data = JsonConvert.DeserializeObject<List<Sale>>(jsonstring);

+1

Source: https://habr.com/ru/post/1690894/


All Articles