【发布时间】: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