7 March, 2012
0 Comments
1 category
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; } } }
Category: Uncategorized
Nice. Looks a lot like PHP’s good ol’ print_r function.