David Munsa
David Munsa

Reputation: 893

C# Deserialize JSON to any type method

so i have this method (the second block of code) that convert any json to c sharp object it works good but

what i want to do his to be able to tell the method which type of object she need to cast to

//not real code

public static object JSONToObj(string i_json, typeof(Home)) //will return an Home object

//not real code

//real code

public static object JSONToObj(string i_json)
{
     serializer = new JavaScriptSerializer();
     object io_obj = serializer.Deserialize<object>(i_json);

     return io_obj;
}

//real code

Upvotes: 2

Views: 341

Answers (1)

krivtom
krivtom

Reputation: 24916

public static T JSONToObj<T>(string i_json)
{
    var serializer = new JavaScriptSerializer();
    T io_obj = serializer.Deserialize<T>(i_json);

    return io_obj;
}

You can call it like this:

Home h = JSONToObj<Home>(json);

Upvotes: 3

Related Questions