What I want to do: Use Activator to dynamically create an object (which could be any type) and pass it to a method for serializing JSON. Note: I have already looked at No type inference with generic extension method but that didn't really give me any useful information on how I could solve this problem.
Edit: Using .NET 3.5 Framework
Problem: The object I receive could be an array (such as int[]) and when I use generics to type the received object, I get an object[] instead of an int[].
Code sample:
class Program
{
static void Main(string[] args)
{
object objArr = new int[0];
int[] intArr = new int[0];
string arrS = "[1,2]";
object objThatIsObjectArray = Serialize(objArr, arrS);//I want this to evaluate as int[]
object objThatIsIntArray = Serialize(intArr, arrS);//this evaluates as int[]
Console.Read();
}
public static object Serialize<T>(T targetFieldForSerialization, string value)
{
return value.FromJson<T>();
}
}
public static class JSONExtensions
{
public static TType FromJson<TType>(this string json)
{
using (var ms = new MemoryStream(Encoding.Default.GetBytes(json)))
{
var ser = new DataContractJsonSerializer(typeof(TType));
var target = (TType)ser.ReadObject(ms);
ms.Close();
return target;
}
}
}