When utilising web services in Microsoft Dynamics 365, you may need to serialize some data to a JSON string. The most convenient way of doing this is to use a .NET library called System.Web, specifically System.Web.Script.Serialization. However, in a sandboxed plugin, access to the System.Web family of libraries is forbidden, throwing an error similar to:
“access security critical method 'System.Web.Script.Serialization.JavaScriptSerializer..ctor()' failed”
This makes serializing a class into JSON a touch more difficult. However, it is still possible to use built in .NET functionality to accomplish this.
This is accomplished by using a built in Runtime serialization class called ‘DataContractJsonSerializer’. This class serializes objects based on tags in the objects structure, and converts this data into JSON format. Thus, in the construction of the class, it is necessary to include these tags to inform the class which attributes to include. This is essentially forming a contract between the serializer and the target class for consumption, so that the serializer can consistently serialize and deserialize these objects.
The information can then be passed into the serializer to encode. In order to do this, you must initialise an instance of the DataContractJsonSerializer with the Type of the target class as a parameter:
In order to actually serialize the object, the serializer must write the object to a memory stream, which can then be read into a string object. The serialization can be performed as follows:
Once in JSON format, the object can then be converted back to the source object by writing the JSON object to a memory stream, then reading the object off the stream using the serializer.
If you are serializing/deserializing multiple different objects however, it may make sense to abstract this functionality and make it more generic, thus being able to be used for multiple different objects. These objects are still required to use the DataContract tags, so make sure you include those when constructing the objects!