Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a JSON string using ASP.NET?

I am using Sendgrid API to send and retrieve statistics of mail sent. I want to store the response of API in database.

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();
}

The response I will get will be like:

[
  {
    "status": "4.0.0",
    "created": "2011-09-16 22:02:19",
    "reason": "Unable to resolve MX host sendgrid.ne",
    "email": "[email protected]"
  },
  {
    "status": "4.0.0",
    "created": "2011-09-19 17:47:15",
    "reason": "Connection timed out",
    "email": "[email protected]"
  }
]

How can i extract value of each of the four fields and store them in table containing four fields?

like image 583
Ami Avatar asked Jan 16 '26 18:01

Ami


1 Answers

If you do not want to create a Movie class, you can use System.Web.Script.Serialization to parse and get a dynamic object.

JavaScriptSerializer js = new JavaScriptSerializer();
dynamic movie = js.Deserialize<dynamic>(json);
like image 118
Rafa Paez Avatar answered Jan 19 '26 19:01

Rafa Paez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!