如何使用ASP.NET解析JSON字符串?

时间:2014-01-28 11:38:26

标签: asp.net json sendgrid

我正在使用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"
  }
]

如何提取四个字段中每个字段的值并将它们存储在包含四个字段的表中?

3 个答案:

答案 0 :(得分:4)

如果您不想创建Movie类,可以使用System.Web.Script.Serialization来解析并获取dynamic对象。

JavaScriptSerializer js = new JavaScriptSerializer();
dynamic movie = js.Deserialize<dynamic>(json);

答案 1 :(得分:2)

要在.NET中读取JSON字符串,我建议使用Newtonsoft Json.NET

这是一个将字符串反序列化为对象并读取属性的简单示例:

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

请注意,您必须提前定义要将值反序列化的对象;您可以看到,在此示例中,已存在类型Movie,并且JsonConverter将JSON字符串中的属性与该类型的属性匹配。

答案 2 :(得分:1)

我得到了答案

     public class BouncesAndBlocks
{
    public string status { get; set; }
    public string created { get; set; }
    public string email { get; set; }
    public string reason { get; set; }
}
     protected void btnBounces_Click(object sender, EventArgs e)
{
    string url = "https://api.sendgrid.com/api/bounces.get.json";
    string JS = GetResult(url);
    List<BouncesAndBlocks> res = (List<BouncesAndBlocks>)JsonConvert.DeserializeObject(JS, typeof(List<BouncesAndBlocks>));
    foreach (var item in res)
    {
        //Store in database
        lbl.Text = "Date:" + item.created.ToString() + "    Status:" + item.status.ToString() + "     Email:" + item.email.ToString() + "       Message:" + item.reason.ToString() + "";

    }
}