Search code examples
c#jsonserializationdynamics-crm

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?


Solution

  • 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