1

I've got this class with a method that returns an object:

public class Deserializer<T>
{
    public static T FromJson(string json)
    {
        return new JavaScriptSerializer().Deserialize<T>(json);
    }   
}

And I've got a Type. How do I create an instance of the Deserializer class based on a this type? The following obviously doesn't work:

var type = typeOf(MyObject);
var foo = Deserializer<type>.FromJson(json);

3 Answers 3

8

You could provide a non-generic version as well for consumers that don't know the type at compile-time (which is a good practice by the way when you are exposing an API):

public class Deserializer
{
    public static T FromJson<T>(string json)
    {
        return new JavaScriptSerializer().Deserialize<T>(json);
    }

    public static object FromJson(string json, Type type)
    {
        return new JavaScriptSerializer().Deserialize(json, type);
    }
}

Now, consumers that know the type at compile-time:

Foo foo = Deserializer.FromJson<Foo>(json);

and consumers that don't know the type at compile-time:

Type type = ...
object instance = Deserializer.FromJson(json, type);
Sign up to request clarification or add additional context in comments.

1 Comment

It works, but remember to reference the right version of System.Web.Extensions (.NET 4/4.5) where the Deserialize method takes type as an argument :)
1

This is how you could do it, but it's not exactly optimal unless you absolutely must do it this way. Go with one of the other answers if you can!

dynamic result = typeof(Deserializer<>).MakeGenericType(type)
    .InvokeMember("FromJson", BindingFlags.Public | BindingFlags.Static |
                              BindingFlags.InvokeMethod, null, null,
                  new [] { json });

2 Comments

+1, Although you will need to create an instance to invoke this method.
I'm sure it works, but holy flying crackerjacks, Batman! That's not really the prettiest of answers :)
0

You can't do this. Generic type parameters are statically bound (compile-time). You can't pass it a System.Type object.

For your simple example, You could (somewhat obviously) just use MyObject:

MyObject foo = Deserializer<MyObject>.FromJson(json);

If you could do this, what would the resultant type of FromJson be? How would you use that object?

Type t = ___;  // How do you get this?
??? foo = Deserializer<t>.FromJson(json);   // What datatype is foo?

What you're trying to do isn't a feature of a statically-typed language like C#. It's more of a dynamic language feature, like Python, where you just return whatever you want and do whatever you want to it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.