【问题标题】:Nested Json deserialize c#嵌套的Json反序列化c#
【发布时间】:2017-12-16 11:17:30
【问题描述】:

我有一个这样的json字符串;

[
  {
    "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"
  }
]

然后像这样建立类;

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; }
}

我用这段代码调用 json 并反序列化;

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;

我得到错误。但是,如果我更改我的 json 并剪切下半部分并删除 [,] 符号代码就可以正常工作。我需要像上面那样反序列化多个并尝试了多种反序列化方法,但这是迄今为止我得到的最接近的方法。

我在这一行得到错误;

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

错误是

无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 .. 等等。

我知道我错过了一些非常基本的东西,但我没有程序员朋友可以问。 如果您能提出更好的方法,我将不胜感激。

【问题讨论】:

  • 错误很明显,您想将对象数组反序列化为单个对象。使用 ICollection 等反序列化集合或确保 json 不包含数组
  • 顺便说一句,你确实有一个程序员朋友:google for json.net 无法反序列化当前 JSON 数组

标签: c# json deserialization


【解决方案1】:

您应该将其反序列化为集合;

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();

【讨论】:

  • 是的,我认为它会起作用,但我将如何使用 ID = data.ID,userInf = data.UserInf.Name,
【解决方案2】:

你可以这样尝试吗,不要使用你已经知道返回类型的 var

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

作为你的字符串返回数据数组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多