Friday, 18 September 2020

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

1 comment: