Question

I saw this method in a sample from Xamarin, using JSON accessing a REST Server:

List<Country> countries = new List<Country>();
    public Task<List<Country>> GetCountries()
    {
        return Task.Factory.StartNew (() => {
            try {

                if(countries.Count > 0)
                    return countries;

                var request = CreateRequest ("Countries");
                string response = ReadResponseText (request);
                countries = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (response);
                return countries;
            } catch (Exception ex) {
                Console.WriteLine (ex);
                return new List<Country> ();
            }
        });
    }

where "CreateRequest" and "ReadResponseText" are methods that interact with a REST Server, basically receiving a list of countries to deserialize and return in the list. So now, I'm trying to make this method generic in order to receive the type and return a generic list of objects of the specified type, something like this:

public static Task<List<Object>> getListOfAnyObject(string requested_object, Type type) 
    {
        return Task.Factory.StartNew (() => {
            try {
                var request = CreateRequest (requested_object);
                string response = ReadResponseText (request);
                List<Object> objects = // create a generic list based on the specified type
                objects = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Object>> (response); // not sure how to handle this line
                return objects;
            } catch (Exception ex) {
                Console.WriteLine (ex);
                return ex.Message;
            }
        });
    }

So my question is, how can I create the method above in order to use it more and less like this (casting the list to my desired type)?

List<Country> countries = (List<Country>)(List<?>) getListOfAnyObject("countries",Country.type);

Many thanks in advance!

Was it helpful?

Solution

Try something like this..

public static Task<List<T>> getListOfAnyObject<T>(string requested_object) 
{
   return Task.Factory.StartNew (() => {
       try {
           var request = CreateRequest (requested_object);
           string response = ReadResponseText (request);
           return Newtonsoft.Json.JsonConvert.DeserializeObject<List<T>> (response); // not sure how to handle this line
       } catch (Exception ex) {
           Console.WriteLine (ex);
           return ex.Message;
       }
   });
}

Called like so..

List<Country> countries = getListOfAnyObject<Country>("countries");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top