Last active
January 13, 2016 21:52
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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