I am getting an error when trying to use a Type parameter when specifying the Type for a generic method.
Error: ‘JsonFilter.JsonDataType’ is a ‘property’ but is used like a ‘type’
public class JsonFilter : ActionFilterAttribute
{
public Type JsonDataType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
...
JavaScriptSerializer jss = new JavaScriptSerializer();
var result = jss.Deserialize<JsonDataType>(inputContent);//Error here
...
New Code
...
JavaScriptSerializer jss = new JavaScriptSerializer();
MethodInfo method = jss.GetType()
.GetMethod("Deserialize")
.MakeGenericMethod(new Type[] { JsonDataType });
var result = method.Invoke(jss, new object[] { inputContent });
filterContext.ActionParameters[Param] = result;
...
Reflection saves the day. Thanks @Jason for the explanation that when type is specified as part of generic method ( <Typename> ), then it gets compiled into bytes. Whereas when as property, it can be any type, only determinable at runtime.
UPDATE
For this specific problem, the following code is more concise.
var o = new DataContractJsonSerializer(JsonDataType).ReadObject(
filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters[Param] = o;
The error
is telling you exactly the problem.
Here, you are trying to pass
JsonDataTypeas a type parameter to the generic methodJavaScriptSerializer.Deserialize<T>but here
you declared
JsonDataTypeas a property of typeType, but not as a type. To use a generic method you need to pass a type parameter (or, in some cases, let the compiler infer one). For examplewould be correct usage as
stringis a type.Now, if you absolutely want to use the type that is represented by
JsonDataTypeyou can use reflection.