First before you start coding, please read this post on how to convert json data to c# class.
How to convert JSON data to Class - C#
After finish convert json data to c# class, write this code to read your json data.
Example JSON Data
{ "name":"swengineercode", "email": [ "swengineercode@gmail.com","swengineercode@gmail.com" ], "websites": { "home_page":"http:\/\/swengineercode.blogspot.com", "blog":"http:\/\/swengineercode.blogspot.com" } }
JSON Class after converted
public class Websites { public string home_page { get; set; } public string blog { get; set; } } public class RootObject { public string name { get; set; } public List<string> email { get; set; } public Websites websites { get; set; } }
C# Code
public DataTable ParseResponse(WebResponse response) { DataTable table = new DataTable(); table.Columns.Add("name", typeof(string)); table.Columns.Add("home_page", typeof(string)); table.Columns.Add("blog", typeof(string)); table.Columns.Add("email", typeof(string)); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { var joResponse = JObject.Parse(reader.ReadToEnd()); var rootObj = JsonConvert.DeserializeObject<RootObject>(joResponse.ToString()); //add new row DataRow row = table.NewRow(); //class string row["name"] = rootObj.name; //class List<string> row["email"] = String.Join("|", rootObj.email); //class website row["blog"] = rootObj.websites.blog; row["home_page"] = rootObj.websites.home_page; table.Rows.Add(row); } return table; }
Note : the example above using JSon.NET library. You can donwload the library here : http://www.newtonsoft.com/json
By Mohd Zulkamal
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
0 comments:
Post a Comment