acidzombie24 acidzombie24 - 1 year ago 92
JSON Question

How do I get formatted json in .NET using C#?

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

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

I would like something nicer like:


My code is something like this:

using System.Web.Script.Serialization;

var ser = new JavaScriptSerializer();
configSz = ser.Serialize(config);
using (var f = (TextWriter)File.CreateText(configFn))

Answer Source

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);

            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; }


  "Sizes": [
  "Price": 3.99,
  "Expiry": "\/Date(1230447600000-0700)\/",
  "Name": "Apple"

Documentation: Serialize an Object

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download