A way to pretty print a C# object

Hui picture Hui · Jun 10, 2011 · Viewed 59.8k times · Source

I have a text box and I want to display a C# object in it in a human-readable way, just for debugging reasons. I don't want to use external libraries if possible. How do I do this?

Answer

Richard picture Richard · Jun 10, 2011

If you use Json then I would suggest using Newtonsofts Json library and then you can output the entire object in Json notation and it will format it with spacing and line breaks. we have used this to display complex objects easily for debug purposes:

var jsonString = JsonConvert.SerializeObject(
           complexObject, Formatting.Indented,
           new JsonConverter[] {new StringEnumConverter()});

here I have also used the String Enum converter in order to display Enums as their string representation rather than as an integer.

The library is available through NuGet as Json.Net or Newtonsoft Json

Or you can get it here:

https://www.newtonsoft.com/json