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

前端 未结 3 1488
暖寄归人
暖寄归人 2020-12-18 15:15

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         


        
相关标签:
3条回答
  • 2020-12-18 15:28

    I got the answer

         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() + "";
    
        }
    }
    
    0 讨论(0)
  • 2020-12-18 15:35

    To read a JSON string in .NET, I recommend using Newtonsoft Json.NET.

    Here is a simple example of deserializing a string into an object and reading a property:

    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
    

    Note that you will have to define the object that you want to deserialize the values into ahead of time; you can see that in this example there is a Type Movie that already exists, and the JsonConverter matches the properties in the JSON string to the properties of that type.

    0 讨论(0)
  • 2020-12-18 15:42

    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);
    
    0 讨论(0)
提交回复
热议问题