Tutorial :Generic method to recive any type of object and convert the object to a List


EDIT AGAIN: the solution was probably different from my original question. Thanks everyone very much your great ideas. I wish I could vote for more than one answer.

EDIT: I am populating a Jquery table plugin from datatables/.net and it requires the data (Json) to be in a certain format like this;

    "sEcho": 1,      "iTotalRecords": 57,      "iTotalDisplayRecords": 57,      "aaData": [          [              "Gecko",              "Firefox 1.0",              "Win 98+ / OSX.2+",              "1.7",              "A"          ],          [              "Gecko",              "Firefox 1.5",              "Win 98+ / OSX.2+",              "1.8",              "A"          ],          ...      ]   }  

I am recieving data from a service that is returning a collection of object. I would like one method which I can pass these collections into and it will return the appropriate string

thanks END EDIT I would like to build a method that can receive and object that we build and will return an array List each containing the value of each object passed in. For example;

I have a collection of 'Car' objects

What I would like to do is

public object[] Something<T>(_cars)  {      object[] objArray = new object[_cars.Count];      foreach(Car _car in _cars ){      IList objList = new List<string>;      objList.Add(_car.Color);      objList.Add(_car.EngineSize);      //etc etc      objArray[i] = objList;//i'll have to use a for loop to get the i counter but you get my idea     }      return objArray  }  

my problem is how can I access the properties of the object without knowing what type of object it is?

thanks for any help


Use the System.Web.Script.Serialization.JavaScriptSerializer class. It was specifically provided for JSON serialization.

using System.Web.Script.Serialization;    public string ToJson(object o)  {    JavaScriptSerializer serializer = new JavaScriptSerializer();    return serializer.Serialize(o);  }  

EDIT: Oops, I missed that your plugin doesn't want a true JSON representation of the objects; it just wants arrays of values. You could use reflection to iterate over the properties of the objects as others have suggested, but then you have no control over which properties end up in which columns. It is not clear from your question whether that is a problem for you.

If you need a strict mapping between properties and columns, then you will have to define that somehow in C#. To do this you could implement IEnumerable as Ed demonstrates or create a custom interface:

public interface ITableDataSource  {    IList<string> GetTableData();  }  

Then implement this on any objects that might need to be data sources for the jQuery table plugin:

public class Car : ITableDataSource  {    //...class implementation details...      public IList<string> GetTableData()    {      return new List<string>()      {        this.Color,        this.EngineSize,        this.NumberOfSeats.ToString()      };    }  }  

Finally, in your method that is returning the data to the jQuery plugin, use the interface to construct your response object, then pass it to my ToJson() method to serialize it:

public string DoSomething(IList<ITableDataSource> objects)  {    var result = new     {      sEcho = 1,      iTotalRecords = 1,      iTotalDisplayRecords = 1,      aaData = new List<IList<string>>()    };    foreach (ITableDataSource ds in objects)      result.aaData.Add(ds.GetTableData());      return ToJson(result);  }  


Update: To answer your revised question - produce a JSON result of a data structure - use the built-in JavaScriptSerializer class:

JavaScriptSerializer serializer = new JavaScriptSerializer();  string json = seriaizer.Serialize(myObjectOrArray);  

Below is the previous answer.

how can I access the properties of the object without knowing what type of object it is

Using Reflection, and grabbing the properties which are strings. Note this is not necessarily a good idea. The fact that you have to use reflection to get what you want is usually a HUGE WARNING FLAG that your design is wrong.

However, in the hopes of learning something useful, here's how it could be done:

public object[] Something<T>(T[] items)  {      IList objList = new List<object>();      //get the properties on which are strings      PropertyInfo[] properties = typeof(T).GetProperties().Where(p => p.PropertyType == typeof(string));      foreach(T item in items)      {          IList stringList = new List<string>;          foreach(PropertyInfo property in properties)          {              objList.Add(property.GetValue(item, null) as string);          }          objList.Add(stringList);      }     }     return objList.ToArray();  }  

A far, far better solution would be to require all the objects coming into this method to conform to some interface that requires them to provide their own string-formatted data. Or maybe take two steps back and ask for help on the underlying problem. This approach is fraught with problems. It's a rabbit hole you don't want to go down.


While it would be relatively straightforward to use reflection to loop through all of your objects and all the properties on those objects to build that string, it's already been written.

I would highly recommend looking at the Json.NET project found here. Add this DLL to your project and converting a list of objects into a Json formatted string is as easy as:

string json = Newtonsoft.Json.JsonConvert.SerializeObject( listOfCars );  


IList objList = new List<string>();  foreach ( PropertyInfo prop in _car.GetType().GetProperties() )  {      var value = prop.GetValue( _car, null );      objList.Add( value != null ? value.ToString() : null );  }  objArray[i] = objList;  


The code to get the Property values of an object is

foreach (PropertyInfo info in myObject.GetType().GetProperties())  {     if (info.CanRead)     {        object o = propertyInfo.GetValue(myObject, null);     }  }   


my problem is how can I access the properties of the object without knowing what type of object it is?

Well, in the general sense you can't. Generics is all about treating objects generically. However, you can impose type constraints by using a where clause. Based on the foreach loop I would say constrain your types to types that implement IEnumerable, but then you go on to use properties like "Color" and "EngineSize", which are very specific. I don't even know why you would have properties named "Color" and "EngineSize" that are strings, but that is another problem altogether...

It seems like the best approach for you would be to define an interface or an abstract base class that each of these objects inherits from. Then you can use the 'where' clause to constrain to objects of that interface/base class only So...

public object[] Something<T>( T _cars) where T : IEnumerable<MyInterface>  

However, if we are going to go down this road I don't see why the method should be generic at all. It could simply take an IEnumerable<T> as an input. When we only want to use one type in a method generics is not needed.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »