在没有根的情况下反序列化 JSON 数组。你如何读取数组值?

Deserializing JSON array without a Root. How do you read the array values?

我正在尝试使用 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# class:

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

您的代码有两个问题:

1 - Json 应该反序列化为 List<Items> 而不是 List<M>
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