With the DataContractSerializer you are able to serialize objects in XML or JSON format, which is then transmitted to the client of the web service. There are two basic approaches to achieve this:. You can simply return an instance of an object and WCF will serialize the object for you in XML or JSON, depending on the specified. You can decorate the type that you will serialize with attribute and all the members that you wish to serialize with attribute While the first approach is simpler, it has some serious drawbacks and second approach is highly recommended.
When preparing types for serialization (placing DataContract and DataMember attributes), you should have following in mind:. Only public members can be serialized when working under medium trust environment. Since Sitefinity CMS does support medium trust environment, you should never mark non-public member with a DataMember attribute. For properties, both getter and setter must be defined and they both have to be public for serialization to work under medium trust environment. Not all types are serializable. For the list of supported types consult following resources:. You can serialize only the instances of types decorated by the DataContract attribute.
To support deserializing an object from the attributes, all you have to do is to implement the IXmlSerializable.ReadXml method. Finally, as the aforementioned MSDN article says about the supported types – you should also be able to use XmlElement/XmlNode types as a way of representing XML directly – the DataContractSerializer, like in this case, take the short route and simply gets the Xml. The attribute can only be applied to whole data contract types. The attribute is applied to an 'outer type' that can be a class or a structure. In its simplest usage, applying the attribute simply specifies a type as a 'known type.' The main difference between the DataContractSerializer and the NetDataContractSerializer is that the.
For any derived types that may be serialized, you need to decorate the type with the KnownTypes attribute and specify the derived type.
How to: Serialize and deserialize JSON data. 2 minutes to read. Contributors. In this article JSON (JavaScript Object Notation) is an efficient data encoding format that enables fast exchanges of small amounts of data between client browsers and AJAX-enabled Web services. This article demonstrates how to serialize.NET type objects into JSON-encoded data and then deserialize data in the JSON format back into instances of.NET types.
This example uses a data contract to demonstrate serialization and deserialization of a user-defined Person type and uses. Normally, JSON serialization and deserialization are handled automatically by Windows Communication Foundation (WCF) when you use data contract types in service operations that are exposed over AJAX-enabled endpoints. However, in some cases you may need to work with JSON data directly.