JsonValue pretty printing
Now that the System.Json API has been released (https://wcf.codeplex.com, https://wcf.codeplex.com/wikipage?title=WCF%20jQuery), I'll start posting a series of "improvements" that I've done over the past few months using that library. Let me know if you find it useful, and I'll bring it to the team to include in future releases of the Codeplex project.
To start, something simple: pretty printing. Like in Silverlight, when calling ToString() in a JsonValue object you get the JSON corresponding to the DOM. But in many cases, it's useful to have it pretty printed, for easier inspection or debugging. This is a simple extension method which accomplishes that.
Extension:
- public static class SystemJsonExtensions
- {
- public static string PrettyPrint(this JsonValue jv)
- {
- StringBuilder sb = new StringBuilder();
- PrettyPrint(sb, jv, 0, true);
- return sb.ToString();
- }
- static void PrettyPrint(StringBuilder sb, JsonValue jv, int indent, bool first)
- {
- if (jv == null)
- {
- AddIndent(sb, indent);
- sb.Append("null");
- }
- else
- {
- int i;
- switch (jv.JsonType)
- {
- case JsonType.Array:
- if (!first)
- {
- AddIndent(sb, indent);
- }
- sb.AppendLine("[");
- for (i = 0; i < jv.Count; i++)
- {
- PrettyPrint(sb, jv[i], indent + 1, false);
- if (i < jv.Count - 1)
- {
- sb.AppendLine(",");
- }
- else
- {
- sb.AppendLine();
- }
- }
- AddIndent(sb, indent);
- sb.Append(']');
- break;
- case JsonType.Object:
- if (!first)
- {
- AddIndent(sb, indent);
- }
- else
- {
- first = false;
- }
- sb.AppendLine("{");
- i = 0;
- foreach (string key in ((JsonObject)jv).Keys)
- {
- PrettyPrint(sb, new JsonPrimitive(key), indent + 1, true);
- sb.Append(": ");
- JsonValue value = jv[key];
- if (value == null || value.JsonType == JsonType.Boolean || value.JsonType == JsonType.Number || value.JsonType == JsonType.String)
- {
- PrettyPrint(sb, value, 0, true);
- }
- else
- {
- PrettyPrint(sb, value, indent + 1, true);
- }
- i++;
- if (i < jv.Count)
- {
- sb.AppendLine(",");
- }
- else
- {
- sb.AppendLine();
- }
- }
- AddIndent(sb, indent);
- sb.Append('}');
- break;
- case JsonType.Boolean:
- case JsonType.Number:
- case JsonType.String:
- AddIndent(sb, indent);
- sb.Append(jv.ToString());
- break;
- }
- }
- }
- static void AddIndent(StringBuilder sb, int indent)
- {
- for (int i = 0; i < indent * 2; i++) sb.Append(" ");
- }
- }
Sample:
- public class Program
- {
- public static void Main(string[] args)
- {
- JsonValue jv = new JsonObject
- {
- { "friends",
- new JsonArray {
- new JsonObject {
- { "Name", "Shaggy" },
- { "Age", 21 },
- { "Known Relatives", null },
- },
- new JsonObject {
- { "Name", "Scooby Doo" },
- { "Age", 8 },
- { "Known Relatives", new JsonArray { "Scrappy-Doo", "Scooby-Dum" } }
- },
- }
- }
- };
- Console.WriteLine(jv.PrettyPrint());
- }
- }