One of the things I missed in the switch from a dynamic language like PHP to a typed language like C# is the ability to easily traverse any object without much care for types. This meant you could implement things like PHP’s incredibly useful print_r() function without too much effort.
I’m now happy to announce that following the release of TypeSerializer we now have that functionality in C#/.NET!
In the ServiceStack.Text.JsvFormatter class are two extension methods which recursively dumps all the public properties of any type into a human readable ‘pretty formatted’ string.
string Dump<T>(this T instance);
string SerializeAndFormat<T>(this T instance);
Both methods achieve the same result. I just wanted to include the logically named but lengthier ‘SerializeAndFormat’ for completion as it describes exactly what it does. Most of the time we don’t care and are happy to use the shortened ‘Dump’ to mean the same thing.
After importing the ServiceStack.Text namespace you can view the value of all fields as seen in the following example:
var model = new TestModel();
Console.WriteLine(model.Dump());
Example Output
{
Int: 1,
String: One,
DateTime: 2010-04-11,
Guid: c050437f6fcd46be9b2d0806a0860b3e,
EmptyIntList: [],
IntList:
[
1,
2,
3
],
StringList:
[
one,
two,
three
],
StringIntMap:
{
a: 1,
b: 2,
c: 3
}
}
I’ve found this feature to be so useful that I’ve included it as part of the JSV endpoint by simply appending &debug anywhere in the request’s query string. So even if you don’t use the new JSV endpoint you can still benefit from it by instantly being able to read the data provided by your web service. Here are some live examples showing the same web services called from the XML and JSV endpoint that shows the difference in readability:
GetNorthwindCustomerOrders
GetFibonacciNumbers?Skip=5&Take=10
All software is released under the liberal New BSD Licence so you are free to start using it in your own projects. You can download it any ONE of the following ways:
Included as part of the Service Stack binaries – ServiceStack/downloads Available as a standalone dll – ServiceStack.Text/downloads
If you want to know more about the Dump’s serialization format and how you can use it to store text blobs in databases check out the introductory post.