从Request.form获取嵌套值

时间:2019-07-15 14:28:23

标签: c# json

我正在尝试从我在c#Webforms中使用“ POST”方法接收的数据中提取一些值,示例数据为:

{  
   "ProductStockDetailsID":8015425,
   "LocationID":24213,
   "ProductID":19284305,
   "MinStock":null,
   "MaxStock":null,
   "OnOrder":0,
   "Alerts":false,
   "ProductStocks":[  
    {  
     "StockID":11839663,
     "CurrentStock":68,
     "CurrentVolume":0,
     "CreatedDate":"2019-06-30T09:58:38.4",
     "DeletedDate":null,
     "CostPrice":0.00000,
     "ProductStockDetailsID":8015425
    }
   ]
}

我使用Request.Form["ProductID"]成功提取了ProductID,但是我无法提取CurrentStock值,因为它看起来是嵌套在ProductStocks中的。

1 个答案:

答案 0 :(得分:1)

为什么不为请求定义类,然后仅解析请求。为此,您需要覆盖

之类的ProcessRequest方法。

public override void ProcessRequest(HttpContext context)
    {

        string json;
        using (var reader = new StreamReader(context.Request.InputStream))
        {
            json = reader.ReadToEnd();
        }
        var data = JsonConvert.DeserializeObject<RequestData>(json);

        base.ProcessRequest(context);

        ProcessRequest(data);
    }
    
 private void ProcessRequest(RequestData data)
 {
 // ... your code 
 }

要解析的类是:

public class RequestData
{
    public int ProductStockDetailsID { get; set; }
    public int LocationID { get; set; }
    public int ProductID { get; set; }
    public object MinStock { get; set; }
    public object MaxStock { get; set; }
    public int OnOrder { get; set; }
    public bool Alerts { get; set; }
    public Productstock[] ProductStocks { get; set; }
}

public class Productstock
{
    public int StockID { get; set; }
    public int CurrentStock { get; set; }
    public int CurrentVolume { get; set; }
    public DateTime CreatedDate { get; set; }
    public object DeletedDate { get; set; }
    public float CostPrice { get; set; }
    public int ProductStockDetailsID { get; set; }
}

现在只需使用data.ProductStocks