0 Comments

If you want to dump the properties of an object into a string (lets say for logging purposes), you can use JSON serialization in C#. The output string is far less bulky than using XML serialization.

using System.Collections.Generic;
using System.Web.Script.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace NewCode.Rli
{
    [TestClass]
    public class NewCodeTester
    {
        [TestMethod]
        public void Test()
        {
            var person = new Person
            {
                FirstName = "John",
                Kids = new List<Person>
                {
                    new Person { FirstName = "Kid", LastName = "One"},
                    new Person { FirstName = "Kid", LastName = "Two"}
                },
                LastName = "Do",
            };
            var serializer = new JavaScriptSerializer();
            string output = serializer.Serialize(person);

            /* Output: 
              {
               "FirstName":"John",
               "LastName":"Do",
               "Kids":
               [
                   {
                       "FirstName":"Kid",
                       "LastName":"One",
                       "Kids":null
                   },
                   {
                       "FirstName":"Kid",
                       "LastName":"Two",
                       "Kids":null
                   }
              ]
             }
           */
        }
    }
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public List<Person> Kids { get; set; }
    }
}

One Reply to “Dump all object properties to a string by using JSON in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts