Skip to content

Instantly share code, notes, and snippets.

@lazarofl
Last active January 13, 2016 21:52
Show Gist options
  • Save lazarofl/dd780b8db7289a823d62 to your computer and use it in GitHub Desktop.
Save lazarofl/dd780b8db7289a823d62 to your computer and use it in GitHub Desktop.
Generic C# extension to retrieve data from web/api and convert then to an object
//using id_token to get user_data information
string token_validation_url = @"https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=";
var result = WebExtensions.GetResultFromWeb<TokenResult>(string.Concat(token_validation_url, id_token));
public class TokenResult
{
public string email { get; set; }
public string email_verified { get; set; }
public string name { get; set; }
public string picture { get; set; }
public string given_name { get; set; }
public string family_name { get; set; }
public string locale { get; set; }
}
public static class WebExtensions
{
public static T GetResultFromWeb<T>(string url) where T : new()
{
using (var webClient = new WebClient())
{
var json_data = string.Empty;
try
{
json_data = webClient.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment