Convert C# Object to JSON string

Hi Everyone,

Check this post for Convert JSON object to C# Object.

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

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

        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.Firstname = "Dynamcis 365";
            myClass.Lastname = "Customer Engagement";

            var memoryStream = new MemoryStream();
            var serializer = new DataContractJsonSerializer(typeof(MyClass));
            serializer.WriteObject(memoryStream, myClass);
            memoryStream.Position = 0;
            StreamReader streamReader = new StreamReader(memoryStream);
            string objectInJSONString = streamReader.ReadToEnd();

            Console.Write(objectInJSONString);
            Console.Read();
        }

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

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

Hope this helps.


Happy Coding
Gopinath

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.