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 reference 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.

One thought on “Convert JSON to Object using C# Code

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s