Serializing/Deserializing JSON in Dynamics CRM 2013/2015 Plugin

Taken from: http://stackoverflow.com/questions/33010055/serializing-deserializing-json-in-dynamics-crm-2013-2015-plugin

I am developing a plugin for Dynamics 2015. The plugin requires some setup information which I thought would be a good idea to use a json object in the unsecure configuration. Also, there’s an external system which is writing some json into a field in the entity that this plugin responds to which I need to extract information from.

I have tried to use JavascriptSerializer object to deserialize the json but I get a System.MethodAccessException, upon doing some research, I have found out that I can’t use the JavascriptSerializer in sandbox mode.

I don’t want to have to ILMerge Json.Net into my assembly, so is there any other way I can serialize/deserialize json in my plugin code?

shareedit

So here’s how I solved this one

Given

string wsData = string.Empty;
plItem.GetType() == typeof(CategoryInfo);

and

[DataContract]
public class CategoryInfo 
{
    [DataMember]
    public string AllPropertiesToSerialize{ get; set; }
} 

then

using (var ms = new MemoryStream())
{
     var js = new DataContractJsonSerializer(typeof(CategoryInfo));
     js.WriteObject(ms, plItem);
     ms.Position = 0;
     var sr = new StreamReader(ms);
     wsData = sr.ReadToEnd();
} 

Thanks to @dbc and @Guido Preite for the pointers

shareedit
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s