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

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


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

Documentation: Serialize an Object


A shorter sample code for Json.Net library

private static string FormatJson(string json){    dynamic parsedJson = JsonConvert.DeserializeObject(json);    return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);}


If you have a JSON string and want to "prettify" it, but don't want to serialise it to and from a known C# type then the following does the trick (using JSON.NET):

using System;using System.IO;using Newtonsoft.Json;class JsonUtil{    public static string JsonPrettify(string json)    {        using (var stringReader = new StringReader(json))        using (var stringWriter = new StringWriter())        {            var jsonReader = new JsonTextReader(stringReader);            var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = Formatting.Indented };            jsonWriter.WriteToken(jsonReader);            return stringWriter.ToString();        }    }}