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.

        public class MyClass 
            public string Firstname { get; set; }
            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();


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

One thought on “Convert C# Object to JSON string

Leave a Reply

Fill in your details below or click an icon to log in: Logo

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