System.Web.Script.Serialization.JavaScriptSerializer or System.Runtime.Serialization.Json.DataContractJsonSerializer? - c#

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.

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.

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.

Difference between JSON Serialization

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

I need a special serializer (C#)

I am looking for a serializer that will match my requirements,
the serializer can be in the .Net framework, an Open-Sorce or a pay-for product (as long as it can b used directly from the code).
now, my requirements are these:
mandatory
Able to handle a cyclic reference.
Automatic, usues either attribute or inheritance in the target class, and then simply writes to the file.
Positive filtering, meaning that in the target class the fields are marked as what to serialize, and not what not to serialize (like [DataMember] in DataContractSerializer and not like [XmlIgnore] in XmlSerializer).
Must use a default constructor.
Supports polymorphism (no things like 'KnownTypes' in DataContractSerializer).
preferable
Generates file as light-wight as possible.
Serialize as fast as possible.
Works on non-public fields.
I checked most of the .Net serializers and tryied to find more online, and came out short,
all of wiche either not supports cyclic reference, polymorphism, or dose not use any constructor.
so right now i'm prettey out of ideas, and i will be glad for some halp.
Thank you!
The closest in the BCL is BinaryFormatter but it is not interoperable.
I would look at Google's Protocol Buffers They are available for a wide range of languages C++, Java, Python and .NET C#.
The problem withe BinaryFormatter is that it is negative filtering (marking the fildes not to serialze) and that it does not use a constractor.
about google Protocol Buffers (or ProtoBuff) i had a chance to work with it and its very complicated and can hardly be refered as automatic

Providing serialization services in a base class that can be used in derived classes

I've implemented a data access library that allows devs to mark up their derived classes with attributes to have them mapped directly to stored procedures. So far, so good. Now I'd like to provide a Serialize() method or override ToString(), and have the derived classes get free serialization into XML.
Where should I start? Will I have to use Reflection to do this?
XML Serialization using XmlSerializer
In the first instance, I would look at the XML Serialization in the .NET Framework that supports serialization of objects to and from XML using an XmlSerializer. There's also an article from Extreme XML on using this serialization framework.
The following links all provide examples of using this approach:
CodeProject article
Microsoft KB article
DotNetJohn - XML Serialization Using C#
ISerializable and SerializableAttribute
An alternative to this would be to use a formatter and the regular SerializableAttribute and ISerializable system of serialization. However, there is no built-in XML formatter for this framework other than the SoapFormatter, so you'd need to roll your own or find a third party/open source implementation.
Roll Your Own
Also, you could consider writing your own system using, for example, reflection to walk your object tree, serializing items according to their serialization visibility, which could be indicated by your own attributes or the existing DesignerSerializationVisibility attributes. The downside to this shown by most implementations is that it expects properties to be publicly read/write, so bear that in mind when evaluating existing custom solutions.
I would start by looking at XmlSerializer.
Hopefully you'll be able to end there too, since it already gives you this functionality :)
You should be able to use the XmlSerializer to perform the serialization of your class
XmlSerializer serializer = new XmlSerializer(this.GetType());
serializer.Serialize(stream, obj);

Categories

Resources