How to use class model as a variable in a function?

Viewed 48

the problem: I need to know the datatype of class models which I can use as a variable in a normal function.

the attempt: I used object as a variable to pass any class Model

public object JsonToModel(string JsonModel, object model)
{
    object getModel = JsonConvert.DeserializeObject<model>(JsonModel);
    return getModel;
}

the result: problem result

the usage: problem usage

string UserJson = HttpContext.Session.GetString("SignedInUser");
User UserObj = utilities.JsonToModel(UserJson);

Note: User is a class Model

if object makes the problem as it can't stand to use class models as a variable. which data type can do this?

1 Answers

try this, using generics

public T JsonToModel<T>(string json)
{
    return JsonConvert.DeserializeObject<T>(json);
}

using

string userJson = HttpContext.Session.GetString("SignedInUser");
User user = utilities.JsonToModel<User>(userJson);

I only can't see what you gain using this util, still it is the same one line of code. Maybe if you add some settings if would make sense.

Related