Reputation: 94
I have a class called RootObject
:
public class RootObject
{
public string Name { get; set; }
public int Age { get; set; }
public int Address { get; set; }
}
public void getdata()
{
WebRequest request = WebRequest.Create("http://addresstojson.com/json.json");
WebResponse response = await request.GetResponseAsync();
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
}
In the last statement of the getdata()
method, the type is passed:
JsonConvert.DeserializeObject</*here*/>(Stream.ReadToEnd())
I would like to pass the type as parameter to the getdata(RootObject)
method.
Is there a way to do this in C# using generics?
Upvotes: 0
Views: 220
Reputation: 34591
The standard way to implement strongly-typed deserialization is this:
public T Get<T>()
{
string json = ...; // get data somehow
return JsonConvert.DeserializeObject<T>(json);
}
It looks like you want to read results asynchronously, so you need to actually return the result as Task<T>
, as well as to use xxxxAsync
versions of methods that read data:
public Task<T> GetData<T>()
{
WebRequest request = WebRequest.Create("http://addresstojson.com/json.json");
using (WebResponse response = await request.GetResponseAsync())
{
using(var stream = new StreamReader(response.GetResponseStream()))
{
string json = await stream.ReadToEndAsync();
T result = JsonConvert.DeserializeObject<T>();
return result;
}
}
}
You can learn more about generics here: https://msdn.microsoft.com/en-us/library/512aeb7t.aspx
Upvotes: 12
Reputation: 94
public static async Task<T> GetData<T>(string add)
{
WebRequest request = WebRequest.Create(add);
WebResponse response = await request.GetResponseAsync();
using (var stream = new StreamReader(response.GetResponseStream()))
{
return JsonConvert.DeserializeObject<T>(stream.ReadToEnd());
}
}
Upvotes: 0