Difference between JSON Serialization - c#

What are the pros and cons of using the following two JSON serialization methods:
System.Web.Script.Serialization
DataContractJsonSerializer

DataContractJsonSerializer
The primary purpose of the DataContractJsonSerializer is to be used with WCF, since one serialization is a big focus of WCF. Also, it is also better equipped to handle complex classes which have only certain properties available for serialization. This class is more strongly typed, has more knowledge about the type(s) it's handling and better error handling for badly-formed JSON.
.
JavaScriptSerializer
This class on the other hand is much better equipped for quick serialization, it's a more cowboy approach. There's less error checking and less control over what properties which are serialized.
Reference

Related

What serializer to use?

I was using DataContractSerializer and so far it provided everything I need.
Now I need two more features and I already know that they are not possible with DataContractSerializer.
I need to be able to serialize some fields as XmlComments
Some members should be serialized directly as Xml-Attribute in the containing object.
XmlSerializer neither supports opt-in nor does it support fields / privates which I need, so unfortunately it's out of the question.
Can I somehow make my own serializer that honors the existing "XmlAttribute"-Attribute and my custom "XmlComment"-Attribute while using DataContractSerializer as base?
Maybe there's already an third-party serializer out there that provides what I need? I didn't find one though.
I wouldn't mind writing a custom serializer but I want to reuse as much existing code as possible.
You can use the XmlSerializer. You are just going to need to implement IXmlSerializable on objects that can't be handled by the default rules and do the heavy lifting yourself. This is still simpler than rolling your own serializer IMO.

How to prevent serialization of delegates when using DataContractSerializer?

I have a couple of entity classes autogenerated by Linq2Sql. I want to have a possibility to serialize them using DataContractSerializer. But when I'm trying to do that I'm getting an exception because DataContractSerializer can't serialize delegates. As I need to serialize only data, I want to exclude delegates from serialization process. How can I do that?
I can't do that using attributes, because the classes are autogenerated.
LINQ2SQL auto-generated classes are not POCO. AFAIK, they even not marked with DataContract attributes and contains a lot of stuff, which will be a pain for DataContractSerializer.
Create your own DTOs and serialize them. This will be more efficient.

When deserializing JSON from within a C# program, should I ever need to use anything other than JavaScriptSerializer?

.NET provides the JavaScriptSerializer class in the
System.Web.Script.Serialization namespace. (provided in System.Web.Extensions.dll)
It was originally intended to support AJAX web server apps, but the class can be used by any application (client, server, hybrid, anything) that serializes and deserializes .NET classes to JSON. I have a desktop app that captures screenshots and uploads to Facebook, and uses this class to deserialize the response.
would I ever want to look elsewhere for JSON deserialization from within .NET?
If so, why? and where would I Look?
If not, then why does JSON.Net exist? Is it strictly for historical purposes? (ie, because it was created by the community before the JavaScriptSerializer).
In my case there are various reasons that prevent me to use JavaScriptSerializer. Here are some of them.
1) Ugly deserialization when dealing with anonymous types
While the usage is fairly straight forward for serialization:
JavaScriptSerializer serializer = new JavaScriptSerializer();
String json = serializer.Serialize(data);
For deserialization however, there is a minor annoyance in that the deserializer accepts a generic type along with the content:
serializer.Deserialize<T>(String s)
this can be a problem if the type T is not known at compile time and needs to be dynamic. The work around is a bit ugly as I learnt 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 });
Please note: according to Dave Ward comment on this answer there's a DeserializeObject() that can be used to prevent this.
2) Cannot handle circular references
I have seen this using Entity Framework, Linq to SQL, NHibernate, NetTiers and even when using Castle's proxy.
According to MS Connect the circular reference exception will be raised when a navigable relation is double-sided (can access both sides of the relation), so the first thing to do is disable one side of the relation. The exception will also be thrown when you use 1:1 relations (or 1:0..1 or any relation causing the creation of an EntityReference type property), in this case the exception will be of type System.Data.Metadata.Edm.AssociationType.
The solution to this is to make the serializer ignore the properties of type EntityReference, using an empty implementation of a class deriving from JavaScriptConverter and registering it using the RegisterConverters method of the JavaScriptSerializer object.
3) Useful features that leads to less testable code
A useful feature of the JavaScriptSerializer is that you can also implement a custom JavaScriptConverter and pass that in to JavaScriptSerializer for fine-grained control over the serialization/deserialization. However, for it to be really useful you need to know the types at compile time and have references to those types. This really limits the usefulness of this feature because by referencing those classes your code becomes tightly coupled so you cannot easily use it in something like an MVC filter.
For these reasons I have often ended up using Json.NET.
Hope this helps!
I use the JavaScriptSerializer on a wide variety of scenarios, it never let me down, and never needed to look elsewhere for other solutions... :)
...but i do know that JSON.net has some added values like LINQ to JSON, which i never needed, and nice JSON formatting but as Serializing goes JavaScriptSerializer does the work fine.

What are the differences between the XmlSerializer and BinaryFormatter

I spent a good portion of time last week working on serialization. During that time I found many examples utilizing either the BinaryFormatter or XmlSerializer. Unfortunately, what I did not find were any examples comprehensively detailing the differences between the two.
The genesis of my curiosity lies in why the BinaryFormatter is able to deserialize directly to an interface whilst the XmlSerializer is not. Jon Skeet in an answer to "casting to multiple (unknown types) at runtime" provides an example of direct binary serialization to an interface. Stan R. provided me with the means of accomplishing my goal using the XmlSerializer in his answer to "XML Object Deserialization to Interface."
Beyond the obvious of the BinaryFormatter utilizes binary serialization whilst the XmlSerializer uses XML I'd like to more fully understand the fundamental differences. When to use one or the other and the pros and cons of each.
The reason a binary formatter is able to deserialize directly to an interface type is because when an object is originally serialized to a binary stream metadata containing type and assembly information is stuck in with the object data. This means that when the binary formatter deserializes the object it knows its type, builds the correct object and you can then cast that to an interface type that object implements.
The XML serializer on the otherhand just serializes to a schema and only serializes the public fields and values of the object and no type information other then that (e.g. interfaces the type implements).
Here is a good post, .NET Serialization, comparing the BinaryFormatter, SoapFormatter, and XmlSerializer. I recommend you look at the following table which in addition to the previously mentioned serializers includes the DataContractSerializer, NetDataContractSerializer and protobuf-net.
Just to weigh in...
The obvious difference between the two is "binary vs xml", but it does go a lot deeper than that:
fields (BinaryFormatter=bf) vs public members (typically properties) (XmlSerializer=xs)
type-metadata based (bf) vs contract-based (xs)
version-brittle (bf) vs version-tolerant (xs)
"graph" (bf) vs "tree" (xs)
.NET specific (bf) vs portable (xs)
opaque (bf) vs human-readable (xs)
As a discussion of why BinaryFormatter can be brittle, see here.
It is impossible to discuss which is bigger; all the type metadata in BinaryFormatter can make it bigger. And XmlSerializer can work very with compression like gzip.
However, it is possible to take the strengths of each; for example, Google have open-sourced their own data serialization format, "protocol buffers". This is:
contract-based
portable (see list of implementations)
version-tolerant
tree-based
opaque (although there are tools to show data when combined with a .proto)
typically "contract first", but some implementations allow implicit contracts based on reflection
But importantly, it is very dense data (no type metadata, pure binary representation, short tags, tricks like variant-length base-7 encoding), and very efficient to process (no complex xml structure, no strings to match to members, etc).
I might be a little biased; I maintain one of the implementations (including several suitable for C#/.NET), but you'll note I haven't
linked to any specific implementation; the format stands under its own merits ;-p
The XML Serializer produces XML and also an XML Schema (implicitly). It will produce XML that conforms to this schema.
One implication is that it will not serialize anything which cannot be described in XML Schema. For instance, there is no way to distinguish between a list and an array in XML Schema, so the XML Schema produced by the serializer can be interpreted either way.
Runtime serialization (which the BinaryFormatter is part of) serializes the actual .NET types to the other side, so if you send a List<int>, the other side will get a List<int>.
That obviously works better if the other side is running .NET.
The XmlSerializer serialises the type by reading all the type's properties that have both a public getter and a public setter (and also any public fields). In this sense the XmlSerializer serializes/deserializes the "public view" of the instance.
The binary formatter, by contrast, serializes a type by serializing the instance's "internals", i.e. its fields. Any fields that are not marked as [NonSerialized] will be serialized to the binary stream. The type itself must be marked as [Serializable] as must any internal fields that are also to be serialized.
I guess one of the most important ones is that binary serialization can serialize both public and private members, whereas the other one works only with public ones.
In here, it provides a very helpful comparison between these two in terms of size. It's a very important issue, because you might send your serialized object to a remote machine.
http://www.nablasoft.com/alkampfer/index.php/2008/10/31/binary-versus-xml-serialization-size/

System.Web.Script.Serialization.JavaScriptSerializer or System.Runtime.Serialization.Json.DataContractJsonSerializer?

What's the difference between the two? Why would you use one over the other?
Found here: http://aaron-powell.spaces.live.com/blog/cns!91A824220E2BF369!150.entry
DataContractJsonSerializer
The primary purpose of the DataContractJsonSerializer is to be used with WCF, since one serialization is a big focus of WCF. Also, it is also better equipped to handle complex classes which have only certain properties available for serialization.
This class is more strongly typed, has more knowledge about the type(s) it's handling and better error handling for badly-formed JSON.
JavaScriptSerializer
This class on the other hand is much better equipped for quick serialization, it's a more cowboy approach. There's less error checking and less control over what properties which are serialized.
Update
As the above link is dead, here is another link: http://kb.cnblogs.com/a/1454030.
Personally, I'd look at Json.NET - this has the advantage of being .NET 2.0 compatible
The JavaScriptSerializer is marked as obsolete in framework 3.5. You shouldn't use it for that reason. However, back to your question. The JavaScriptSerializer doesn't require classes to be marked as [Serializable] or as [DataContract] but the DataContractJsonSerializer does. If you have compiled classes that you can't mark with attributes, you may want to use the older JSON serializer.

Categories

Resources