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

One thought on “Convert C# Object to JSON string

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