In my case, there are various reasons that prevent me from using JavaScriptSerializer . Here are some of them.
1) Horrible deserialization when working with anonymous types
Although the use is pretty straightforward for serialization:
JavaScriptSerializer serializer = new JavaScriptSerializer(); String json = serializer.Serialize(data);
However, for deserialization, a minor annoyance is that the deserializer takes on a generic type along with its contents:
serializer.Deserialize<T>(String s)
This can be a problem if the type T is unknown at compile time and must be dynamic. The work around is a little ugly, as I found out, because it uses reflection to create a generic method (but it works)
var result = typeof(JavaScriptSerializer).GetMethod("Deserialize") .MakeGenericMethod(JsonDataType) .Invoke(serializer, new object[] { inputContent });
Strike>
Please note : according to Dave Ward, the comment on this answer is DeserializeObject()
, which can be used to prevent this.
2) Unable to execute circular links
I have seen this with Entity Framework , Linq to SQL, NHibernate, NetTiers, and even when using Lock Proxy .
According to MS Connect, a circular link exclusion will be raised when the shipping relationship is two-way (you can access both sides of the relationship), so the first thing to do is disconnect one side of the relationship. An exception will also be thrown if you use a 1: 1 relationship (or 1: 0..1 or any relation that causes the creation of a property of type EntityReference), in which case the exception will be of type System.Data.Metadata.Edm.AssociationType
.
The solution to this is to make the serializer ignore properties of type EntityReference using an empty implementation of the class derived from the JavaScriptConverter and register it using the RegisterConverters method of the JavaScriptSerializer object.
3) Useful functions that result in less verifiable code
A useful feature of JavaScriptSerializer is that you can also implement your own JavaScriptConverter and pass this to the JavaScriptSerializer for fine-grained serialization / deserialization control. However, in order to be really useful, you need to know the types at compile time and refer to these types. This really limits the usefulness of this function, because referring to these classes, your code becomes closely related, so you cannot easily use it in something like an MVC filter.
For these reasons, I often get Json.NET.
Hope this helps!