我正在接收以JSON字符串返回的产品菜单。从这些数据中,我试图填充产品型号列表,并发送到我的视图以作为实时菜单类型显示。我用于检索数据的代码如下:排除正在正确接收所有内容时发送的标头;
var response = await httpClient.SendAsync(request);
var responseContent = response.Content.ReadAsStringAsync().Result;
List<MenuItem> Products = new List<MenuItem>();
JObject jsonObject = JObject.Parse(responseContent);
JToken item = jsonObject["data"];
foreach (var menuitem in item)
{
MenuItem product = new MenuItem(menuitem);
Products.Add(product);
}
我的MenuItem模型正在接收每个单独的项目,并试图设置模型值;
public class MenuItem
{
public MenuItem(JToken product)
{
Id = (Int32)product["id"];
Name = (string)product["name"];
Item_Number = (string)product["item_number"];
Description = (string)product["description"];
Pricing.Default_Price = (string)product["pricing"]["default_price"];
Pricing.Pricing_Group_Id = (Int32)product["pricing"]["pricing_group_id"];
}
该模型还有更多内容,但这应该是所有需要的
public Pricing Pricing { get; set; }
}
public class Pricing
{
public string Default_Price { get; set; }
public Int32 Pricing_Group_Id { get; set; }
public string Pricing_Group_Name { get; set; }
public WeightPrices Weight_Prices { get; set; }
}
public class WeightPrices
{
public Int32 Pricing_Weight_Id { get; set; }
public String Name { get; set; }
public float Default_Price { get; set; }
}
我遇到的问题是试图从更深的子元素中设置定价值。
Pricing.Default_Price = (string)product["pricing"]["default_price"];
Pricing.Pricing_Group_Id = (Int32)product["pricing"]["pricing_group_id"];
我的代码抛出为“对象引用未设置为对象实例”。当它碰到那些线。在VS2017中添加手表时,该值正确,但是我仍然收到此错误。 JSON字符串的格式为;
{"data": [
{
"id": 2148487,
"name": "3.5 grams of Blue Dream",
"item_number": "8AEO00000001",
"description": "",
"pricing": {
"default_price": "20.00",
"pricing_group_id": 5908,
"weight_prices": [
{
"pricing_weight_id": 21504,
"default_price": "12.00",
"name": ".5g",
"uom": "GR",
"weight": 0.5
},
{
"pricing_weight_id": 21505,
"default_price": "20.00",
"name": "1g",
"uom": "GR",
"weight": 1
}
],
"pricing_group_name": "Top Shelf"
}
任何帮助将不胜感激,我还没有开始研究重量,这是下一步。
答案 0 :(得分:2)
Pricing
属性从未实例化,因此,当您尝试在其上设置属性值时,该属性为null。
设置Default_Price
之前,先设置Pricing = new Pricing()