Hello, I am trying to make a dynamic method to which I pass a class as a parameter and it returns that class with unrealized data from an api.
The idea is that I pass, for example, the following class as a parameter:
public class Temperatures
{
[JsonProperty("countryId")]
public object CountryId { get; set; }
[JsonProperty("website")]
public object Website { get; set; }
}
And that I can pass that class to a method that deserealizes the response of an API with newtonsoft and deserealizes the response in the type of class that is passed to it and returns a list of Temperatures. The idea is that you can pass any class to it as a parameter to make it dynamic.
public static Type convertir(Type t,string payload)
{
var obj = JsonConvert.DeserializeObject<t>(payload);
return obj;
}
So you can do something like that and get the list of Temperatures or any other class right away.
List<Temperatures> temps=convertir(typeof(Temperatures),json));
The problem is that Visual Studio won't let me pass t to it in deserealization (JsonConvert.DeserealizeObject<t>)
, nor will it let me pass it to it in this other way: ( JsonConvert.DeserealizeObject<typeof(Temperatures)>
)
For a class to receive T, you must declare it as such, so in the example the class and the object it receives as a parameter are declared and the result of the method is T. It will only be missing between the lesser and greater signs
<T>
, pass itT
,In your example I see the parameter
t
that receives which you should only receive the string withjson
which you want to undo.