I’ve been looking around for ways to parse a JSON string and I’ve come across these two methods.
class Test {
String test;
String getTest() { return test; }
String setTest(String test) { test = test; }
}
var ser = new JavaScriptSerializer();
Test abc = (Test)ser.DeserializeObject("{ \"test\":\"some data\" }");
and
var ser = new JavaScriptSerializer();
Test abc = ser.Deserialize<Test>("{ \"test\":\"some data\" }");
The first one is casting an object to a type and the second one is specifying the type? Any real differences between them? Is one method more preferable?
The second option (using the generic
Deserialize<T>method) is preferable for your particular example since you expect a specific type.Both produce a slightly different outcome when the input doesn’t represent an object of the type you expect. In the first case, you get an InvalidCastException in your cast, and in the second case the Deserialize method throws an InvalidOperationException. But other than that, there is no difference in terms of performance etc. In fact the documentation for
Deserialize<T>states this: