Normally when generating Json you would serialize typed .net objects. In most cases this is the right way to go, but if you have important reasons not to use this approach, for example if the format of the coming data cannot be predicted at compile time and you don’t want to generated dynamically typed objects, for performance reasons, you may consider generating Json code as string. A common way to go is to use StringBuilder, but I would not call it as a very json friendly tool, so here is an alternative.

Json builder can help you iterate through collections and hide json related string transformations from you. Here is how you use it:

var dict = new Dictionary<string, Dictionary<string, string[]>>
   {
       {"First", new Dictionary<string, string[]>
                     {
                         {"First-One", new[]{"1", "2", "3"}},
                         {"First-Two", new[]{"4", "5"}}
                     } 
       },
       {"Second", new Dictionary<string, string[]>
                     {
                         {"Second-One", new[]{@"""Value1""", @"""Value2"""}},
                         {"Second-Two", new[]{@"""Value3"""}}
                     } 
       }
   };



var jb = new JsonBuilder();
jb.FormatIndent = true;
jb.ForEachObjectElement(dict, codes =>
        {
            jb.AppendPropertyName(codes.Key);
            jb.ForEachObjectElement(codes.Value, langs =>
                {
                    jb.AppendPropertyName(langs.Key);
                    jb.ForEachArrayElement(langs.Value, val => jb.Append(val));
                }
                
            );
        });

And this is the result

{
    "First": {
        "First-One": [1,2,3],
        "First-Two": [4,5]
    },
    "Second": {
        "Second-One": ["Value1","Value2"],
        "Second-Two": ["Value3"]
    }
}

You can download the JsonBuilder class from here: JsonBuilder.cs

Share this post:   digg     Stumble Upon     del.icio.us     E-mail

Commenting temporarily disabled