Desrialize and Serialize Json in plugin without newtonsoft library

Often developers struggle with how to handle Json in Plugins, this blog is a way how to serialize and deserialize JSON in plugins without using Imerge or using the new plugin package. Using the method which involves only C# and the default system library, developers can easily serialise and deserialize JSON data.

In the example below, I have created a class that takes a generic T class and then using memory stream to read its value;

public class HandleJson
    {
        public string Serialize<T>(T classObj) where T : class, new()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer serialiaze = new DataContractJsonSerializer(typeof(T));
                serialiaze.WriteObject(ms, classObj);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }

        public T DeSerialize<T>(string classObj) where T : class, new()
        {
            DataContractJsonSerializer deSerialiaze = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(classObj)))
            {
                return deSerialiaze.ReadObject(ms) as T; 
            }

        }

    }

This class can then be called in your plugin class that generates the dll, like the below;

  public class PluginClass : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);


            if (!context.InputParameters.Contains("Target")) return;

            Automobile automobile = new Automobile()
            {
                DoorType = "CYLINDER",
                Name = "Mercedes",
                TyreNumber = 4
            };

            HandleJson jsonSerialiser = new HandleJson();

            //serialize
            var cars = jsonSerialiser.Serialize(automobile);

            //deserialize
            var getCars = jsonSerialiser.DeSerialize<Automobile>(cars);
        }
    }

    public class Automobile
    {
        public string DoorType { get; set; }
        public string Name { get; set; }
        public int TyreNumber { get; set; }
    }

As can be seen above, I have created a class called Automobile, then created an object of the automobile in my plugin class, then finally, used my HandleJson instance to serialize and deserialize the automobile object.