I want to create a generic method for my Service Request and Response with RestSharp. I want to pass resource url and Object Name of any class and hope to get the response of the same object type which I passed.
I am not finding a way to run this code and I know its not the perfect way, but I will be glad if anyone direct me to correct path e.g.
class Employee
{
Employee em = new Employee();
RequestClass CreateRequest = new Request();
public Employee GetAllEmployee()
{
return RequestClass.MyRequest("http://get-all-employee",em);
}
}
class RequestClass
{
public Type MyRequest(string resource, Type objectName)
{
var client = new RestClient("http://Service-url.com");
var request = new RestRequest(resource, Method.GET);
var response = client.Execute(request);
var result = response.Content;
Type ClassName = objectName.GetType();
Object myobject = Activator.CreateInstance(ClassName);
JsonDeserializer jsonDeserializer = new JsonDeserializer();
myobject = jsonDeserializer.Deserialize<Type ClassName>(response);
return (Type)myobject;
}
}
Use a generic type parameter with a new() constraint:
public T MyRequest<T>(string resource) where T : new()
{
var client = new RestClient("http://Service-url.com");
var request = new RestRequest(resource, Method.GET);
var response = client.Execute(request);
JsonDeserializer jsonDeserializer = new JsonDeserializer();
return jsonDeserializer.Deserialize<T>(response);
}
And then use it like this:
public Employee GetAllEmployee()
{
var requestClass = new RequestClass();
return requestClass.MyRequest<Employee>("http://get-all-employee");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With