C# – Why does DataContractJsonSerializer not include generic like JavaScriptSerializer

cwcf

So the JavaScriptSerializer was deprecated in favor of the DataContractJsonSerializer.

var client = new WebClient();
var json = await client.DownloadStringTaskAsync(url); // http://example.com/api/people/1

// Deprecated, but clean looking and generally fits in nicely with 
// other code in my app domain that makes use of generics
var serializer = new JavaScriptSerializer();
Person p = serializer.Deserialize<Person>(json);

// Now have to make use of ugly typeof to get the Type when I 
// already know the Type at compile type. Why no Generic type T?
var serializer = new DataContractJsonSerializer(typeof(Person));
Person p = serializer.ReadObject(json) as Person;

The JavaScriptSerializer is nice and allows you to deserialize using a type of T generic in the function name. Understandably, it's been deprecated for good reason, with the DataContractJsonSerializer, you can decorate your Type to be deserialized with various things so it isn't so brittle like the JavaScriptSerializer, for example

[DataMember(name = "personName")]
public string Name { get; set; }

Is there a particular reason why they decided to only allow users to pass in the Type?

Type type = typeof(Person);

var serializer = new DataContractJsonSerializer(type);
Person p = serializer.ReadObject(json) as Person;

Why not this?

var serializer = new DataContractJsonSerializer();
Person p = serializer.ReadObject<Person>(json); 

They can still use reflection with the DataContract decorated attributes based on the T that I've specified on the .ReadObject<T>(json)

Best Answer

JavaScriptSerializer does not seem to be deprecated, based on current MSDN documentation. It was un-obsoleted with .NET 3 SP1 (see the comment from Microsoft). Examples of it's usage also appears in current Microsoft Learning publications.

I'm not sure then if the DataContractJsonSerializer approach is necessarily superior than the other. But of course, some benchmarks might be interesting :)

Related Topic