2

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

1 Answer 1

3
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);
Sign up to request clarification or add additional context in comments.

11 Comments

and how should i call this method ?
@dotnetom You need to add a constraint where T : new() for the type to be deserializable
Updated types. You can't return an object for type T.
@YuvalItzchakov If that were the case, wouldn't the Deserialize method have that same constraint? But it doesn't: msdn.microsoft.com/en-us/library/bb355316(v=vs.110).aspx
@YuvalItzchakov - If Deserialize had new() restriction, then the same restriction would be required here
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.