Why does DataContractJsonSerializer not include generic like JavaScriptSerializer?
Posted
by
Patrick Magee
on Programmers
See other posts from Programmers
or by Patrick Magee
Published on 2013-05-26T02:08:11Z
Indexed on
2013/06/25
16:28 UTC
Read the original article
Hit count: 317
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)
© Programmers or respective owner