Monday 31 August 2020

Convert JSON to Object using C# Code

Hi Everyone,

Many times we get a requirement to convert JSON string to C# Object and most of the times, we go with Newtonsoft Dll. In Dynamics 365 Plugins, we all know it is not recommended to use Newtonsoft as we have to use ILMerge to merge the dlls and deploy.

Here is the easy way to convert JSON string to C# object without using external references.

You have to add below references from .net framework to your project.

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;

        [DataContract]
        public class MyClass
        {  
            [DataMember]
            public string Firstname { get; set; }
            [DataMember]
            public string Lastname { get; set; }
        }

        static void Main(string[] args)
        {
            // string strJSONstring = Console.ReadLine();
            string strJSON = "{\"Firstname\":\"Dynamics 365\", \"Lastname\":\"Customer Engagement\"}";
            MyClass objMyClass = null;
            using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(strJSON)))
            {
                DataContractJsonSerializer deSerializer = new DataContractJsonSerializer(typeof(MyClass));
                objMyClass = (MyClass)deSerializer.ReadObject(stream);
            }
        }

Hope this helps.

--
Happy Coding
Gopinath.

2 comments: