我使用Sendgrid API发送和检索发送的邮件的统计信息.我想将API的响应存储在数据库中.
protected void btnBounces_Click(object sender,EventArgs e) { try { string url = "https://api.sendgrid.com/api/bounces.get.json"; GetResult(url); } catch (Exception ex) { lblError.Text = ex.Message.ToString(); } } public void GetResult(string url) { string parameters = "api_user=xxxx&api_key=xxxx&date=1&start_date="+txtStartDate.Text+"&end_date="+txtEndDate.Text; // Start the request HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; StreamWriter streamWriter = new StreamWriter(req.GetRequestStream()); streamWriter.Write(parameters); streamWriter.Flush(); streamWriter.Close(); // Get the response HttpWebResponse res = (HttpWebResponse)req.GetResponse(); StreamReader streamReader = new StreamReader(res.GetResponseStream()); string result = streamReader.ReadToEnd(); }
我将得到的回应如下:
[ { "status": "4.0.0","created": "2011-09-16 22:02:19","reason": "Unable to resolve MX host sendgrid.ne","email": "esting@sendgrid.ne" },{ "status": "4.0.0","created": "2011-09-19 17:47:15","reason": "Connection timed out","email": "rawest@gmail.co" } ]
如何提取四个字段中每个字段的值并将它们存储在包含四个字段的表中?
解决方法
如果您不想创建Movie类,可以使用System.Web.Script.Serialization来解析并获取动态对象.
JavaScriptSerializer js = new JavaScriptSerializer(); dynamic movie = js.Deserialize<dynamic>(json);