JSON Deserialization on REST API C#

When facing with REST API, normally the best way to handle the data results would be to use JSON as your content-type , don’t forget to include the library┬áSystem.Web.Script.Serialization is used alongside. ┬áLet’s look at the code on how to simple it is to parse the data coming from your Web API request (REST DATA).

Normally you would be given a credential to access your API, depending on authentication, for this example we’ll be using just the basic one.

string restURL = "http://rest.com/api/v1/params"; 
WebRequest req = WebRequest.Create(restUrl);
            req.Method = "GET";
            req.ContentType = "application/json";
            req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username+":"+password));
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
 if(resp.StatusCode == HttpStatusCode.OK) 
StreamReader reader = new StreamReader( resp.GetResponseStream());
 var objText = reader.ReadToEnd();
 var obj = JsonConvert.DeserializeObject<APiObj>(objText);
 //do whatever you want with this object

Now you’ll have to create POCO class here to map your results to your object.

public class APiObj
         public List<MembershipObj> MemberData { get; set; }
    //actual data object from SNOW
    public class MembershipObj {
        public string Amount { get; set; }
        public string City { get; set; }
        public string Contact { get; set; }
        public string Email { get; set; }
        public string FirstName { get; set; }

And that’s it, as you can see it’s really easy you just need to be aware about the way your results is structured, JSON results will always be in an array just keep that in mind.



Leave a Reply

Your email address will not be published. Required fields are marked *