1

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)

  • Because someone decide it's better to analyze (reflect) the type at the DataContractJsonSerializer constructor? – rwong May 26 '13 at 2:17
  • So performance would be the answer or what? – Patrick Magee May 26 '13 at 2:19
  • This explains the cost comparison between various generics and reflections stackoverflow.com/questions/10202365/… – rwong May 26 '13 at 2:19
  • Sorry that's just my guess. that's why I'm not putting it as an answer. – rwong May 26 '13 at 2:20
  • In case you don't know use json.net as it is superior to both json.codeplex.com – softveda May 26 '13 at 4:03
2

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.