【问题标题】:Deserializing JSON array without a Root. How do you read the array values?反序列化没有根的 JSON 数组。你如何读取数组值?
【发布时间】:2020-07-03 15:03:34
【问题描述】:

我正在尝试使用 Newtonsoft 反序列化一个数组,以便显示值列表,但无论我尝试什么,我都会收到此错误:Exception thrown: 'System.NullReferenceException'

这是我的 JSON:

[
  {
    "M": {
      "ItemNo": {
        "S": "111803"
      },
      "Name": {
        "S": "Viper HD 10 x 50 RP Bi"
      },
      "Price": {
        "N": "549.99"
      },
      "Quantity": {
        "N": "1"
      }
    }
  },
  {
    "M": {
      "ItemNo": {
        "S": "111715"
      },
      "Name": {
        "S": "Cantilever / 2\" Of"
      },
      "Price": {
        "N": "89.99"
      },
      "Quantity": {
        "N": "1"
      }
    }
  }
]

这是我的 C# 类:

public class ItemNo
{

    [JsonProperty("S")]
    public string S { get; set; }
}

public class Name
{

    [JsonProperty("S")]
    public string S { get; set; }
}

public class Price
{

    [JsonProperty("N")]
    public string N { get; set; }
}

public class Quantity
{

    [JsonProperty("N")]
    public string N { get; set; }
}

public class M
{

    [JsonProperty("ItemNo")]
    public ItemNo ItemNo { get; set; }

    [JsonProperty("Name")]
    public Name Name { get; set; }

    [JsonProperty("Price")]
    public Price Price { get; set; }

    [JsonProperty("Quantity")]
    public Quantity Quantity { get; set; }
}

public class Items
{

    [JsonProperty("M")]
    public M M { get; set; }
}

我的代码反序列化并显示第一个数组项值但出现空引用错误:

List<M> mItems = JsonConvert.DeserializeObject<List<M>>(itemsJson);
Console.WriteLine("Items Line Count: " + mItems.Count);
Console.WriteLine("Items#: " + mItems[0].ItemNo.S);
Console.WriteLine("ItemsNam: " + mItems[1].ItemName.S);
Console.WriteLine("ItemsPrc: " + mItems[3].Price.N);

【问题讨论】:

    标签: c# json json.net json-deserialization


    【解决方案1】:

    代码中有两个问题:

    1 - Json 应该被反序列化为 List&lt;Items&gt; 而不是 List&lt;M&gt;
    2 - mItems[3] 会给你一个例外,因为集合只包含两个元素。

    将代码改为:

    List<Items> mItems = JsonConvert.DeserializeObject<List<Items>>(json1);
    Console.WriteLine("Items Line Count: " + mItems.Count);
    
    foreach(Items item in mItems)
    {
        Console.WriteLine($"No :{item.M.ItemNo.S}, Name :{item.M.Name.S}, Price :{item.M.Price.N}, Quantity :{item.M.Quantity.N}");
    }
    

    结果

    Items Line Count: 2
    No :111803, Name :Viper HD 10 x 50 RP Bi, Price :549.99, Quantity :1
    No :111715, Name :Cantilever / 2" Of,     Price :89.99,  Quantity :1
    

    【讨论】:

      猜你喜欢
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      相关资源
      最近更新 更多