tags:

views:

135

answers:

3

I am using .NET json parser and i would like to serialize my config file so it is readable instead of

{"blah":"v", "blah2":"v2"}

to something nicer like

{
    "blah":"v", 
    "blah2":"v2"
}

my code is something like

                using System.Web.Script.Serialization; 

                var ser = new JavaScriptSerializer();
                configSz = ser.Serialize(config);
                using (var f = (TextWriter)File.CreateText(configFn))
                {
                    f.WriteLine(configSz);
                    f.Close();
                }
+4  A: 

Try Json.Net library to format it.

Mendy
+6  A: 

You are going to have a hard time accomplishing this with JavaScriptSerializer.

Try JSON.Net.

With minor modifications from JSON.Net example

using System;
using Newtonsoft.Json;

namespace JsonPrettyPrint
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Product product = new Product
                {
                    Name = "Apple",
                    Expiry = new DateTime(2008, 12, 28),
                    Price = 3.99M,
                    Sizes = new[] { "Small", "Medium", "Large" }
                };

            string json = JsonConvert.SerializeObject(product, Formatting.Indented);
            Console.WriteLine(json);

            Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
        }
    }

    internal class Product
    {
        public String[] Sizes { get; set; }
        public decimal Price { get; set; }
        public DateTime Expiry { get; set; }
        public string Name { get; set; }
    }
}

Results

{
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ],
  "Price": 3.99,
  "Expiry": "\/Date(1230447600000-0700)\/",
  "Name": "Apple"
}
Sky Sanders
There's also an example of formatting json output on his blog http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
R0MANARMY