Monday, July 17, 2017

How to Serialize Using C sharp



Serialize means changing the object in JSON key value pair. Following is a method to serialize the objects in C sharp.

class Program
    {
        static void Main(string[] args)
        {

            Boy objBoy = new Boy();
            objBoy.FirstName = "FirstName";
            objBoy.LastName = "Lastname";
            objBoy.SchoolName = "School";
            objBoy.Number = 100;
            objBoy.CycleColor = "Color";

            //Uncomment below line to test serialization
            Console.WriteLine(JsonSerializeMethod(objBoy));

            //Uncomment below line to test deserialization
            //Person objPerson1 = new Person();
            //string str = JsonSerializeMethod(objBoy);
            //var result = JsonDeserializeMethod(str);

            //var results = JsonConvert.DeserializeObject<dynamic>(str);

            //Console.WriteLine(objPerson1.FirstNameOfPerson);

            Console.ReadLine();
        }
//Here is the link on How to fix 404 Issue
        public static string JsonSerializeMethod(object o)
        {
            var str = JsonConvert.SerializeObject(o);
            return str;
        }

        public static object JsonDeserializeMethod(string str)
        {
            var results = JsonConvert.DeserializeObject<dynamic>(str);
            return results;
        }

        public class Boy
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string SchoolName { get; set; }
            public int Number { get; set; }
            public string CycleColor { get; set; }
        }

        public class Person
        {
            public string FirstNameOfPerson     { get; set; }
            public string LastNameOfPerson      { get; set; }
            public string SchoolNameOfPerson    { get; set; }
            public string PhoneNumberOfPerson   { get; set; }
            public string CycleColorOfPerson    { get; set; }

            public static explicit operator JObject(Person v)
            {
                throw new NotImplementedException();
            }
        }
    }

//A great post on Job Flip Guidance and Improving Relations With Boss

No comments:

Post a Comment