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
    {
        [JsonProperty("result")]
         public List<MembershipObj> MemberData { get; set; }
    }
 
    //actual data object from SNOW
    public class MembershipObj {
 
        [JsonProperty("amount")]
        public string Amount { get; set; }
 
        [JsonProperty("city")]
        public string City { get; set; }
 
        [JsonProperty("contact")]
        public string Contact { get; set; }
 
        [JsonProperty("email")]
        public string Email { get; set; }
 
        [JsonProperty("first_name")]
        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 *