Get Prettified JSON from MVC 3 JsonResult

14,447

Solution 1

Not much of an answer, but if you switch your Json serializer from the built in one (JavaScriptSerializer) to Json.NET (which has a bunch of advantages beyond this issue), you can do something like this :

JsonConvert.SerializeObject( myObjectDestinedForJSON, Formatting.Indented);

Docs on the settings here : http://james.newtonking.com/projects/json/help/

Solution 2

Pragmatic and useful for all situations:

Use chrome + this extension: https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc

this will pretty-format JSON when it realizes it is json.

Share:
14,447
bopapa_1979
Author by

bopapa_1979

I've been writing software for a living since my sophomore year in High School. I like to think I'm good at it, mostly. I have also doubled as a systems administrator, entrepeneur, business developer, and sometimes as a CTO of small companies. While I'm always interested in the latest and slickest approach to crafting software, I try to stay pragmatic and tend to think about technology in terms of revenues. My technology strengths are in Database Design and Programming (not so much optimization) and middleware. I'm very good at turning business rules into decision trees, and like to apply rules from the bottom up. I'm into SQL Server (and other flavors of SQL), .Net, C#, and building Web Applications. I'm slowly jumping on the web 2.0 bandwagon, and JavaScript, which was the red-headed stepchild of languages when I cut my web design teeth, is my next target to become an expert at.

Updated on June 08, 2022

Comments

  • bopapa_1979
    bopapa_1979 almost 2 years

    Context
    Language: C#
    Platform Version: Microsoft .Net Framework 4.0
    Operating System: Windows 7 Professional (64-bit)
    Constraints: Microsoft MVC.Net 3.0

    Problem
    I find myself looking at JSON a lot in a browser these days, pointing a browser at one Controller Action or another on my local dev server and parsing JSON visually to make sure everything is being formatted the way we want. The JSON returned by the MVC 3 serializer (or the JSON.Net serializer) always return a minified string, so I wind up with something like this:

    {"Bars":[{"Name":"Ghost Bar","Address":"2440 Victory Park Lane, 33rd Floor, Dallas, TX 75219","OpenDate":"\/Date(1208062800000)\/","Status":"Open"},{"Name":"M-Street Bar","Address":"5628 Sears Street, Dallas, TX 75206","OpenDate":"\/Date(1064811600000)\/","Status":"Closed"},{"Name":"Zephyr\u0027s Lounge","Address":"3520 Greenville Avenue, Dallas, TX 75206","OpenDate":"\/Date(981007200000)\/","Status":"Open"}]}
    

    Question
    I'd really like to find a way, at least during debugging, to get the JsonResult to be "prettified" so that it looks more like this:

    {
      "Bars": [
        {
          "Name": "Ghost Bar",
          "Address": "2440 Victory Park Lane, 33rd Floor, Dallas, TX 75219",
          "OpenDate": "\/Date(1208062800000)\/",
          "Status": "Open"
        },
        {
          "Name": "M-Street Bar",
          "Address": "5628 Sears Street, Dallas, TX 75206",
          "OpenDate": "\/Date(1064811600000)\/",
          "Status": "Closed"
        },
        {
          "Name": "Zephyr\u0027s Lounge",
          "Address": "3520 Greenville Avenue, Dallas, TX 75206",
          "OpenDate": "\/Date(981007200000)\/",
          "Status": "Open"
        }
      ]
    }
    

    I am aware of several online tools that will let you paste and format JSON. The is an extra step, and is costing me a lot of time. I'd prefer a programmatic solution. I'd also like to be able to turn it on/off via configuration or an #if compiler directive.

    I have already done a cursory search regarding this and come across this post on Stack Overflow. However, the code example given is quite incomplete. There are also a couple of links provided but they appear to be dead.

    In any case, I'd like to find a way to get "prettified" JSON out of an ActionResult. Any help appredciated.

    The following source code will reproduce the initial un-prettified JSON string I gave as an example. Feel free to copy/pasted/edit.

    using System.Collections.Generic;
    using System.Text;
    using System.Web.Mvc;
    
    namespace PrettyJsonResult.Controllers
    {
        public class DefaultController : Controller
        {
            public JsonResult Index()
            {
                var foo = new Foo();
                foo.Bars.Add(new Bar { Address = "2440 Victory Park Lane, 33rd Floor, Dallas, TX 75219", Name = "Ghost Bar", Status = "Open" });
                foo.Bars.Add(new Bar { Address = "5628 Sears Street, Dallas, TX 75206", Name = "M-Street Bar", Status = "Closed" });
                foo.Bars.Add(new Bar { Address = "3520 Greenville Avenue, Dallas, TX 75206", Name = "Zephyr's Lounge", Status = "Open" });
    
                return Json(foo, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
            }
    
        }
    
        public class Foo
        {
            public Foo()
            {
                Bars = new List<Bar>();
            }
    
            public List<Bar> Bars { get; set; }
        }
    
        public class Bar
        {
            public string Name { get; set; }
            public string Address { get; set; }
            public string Status { get; set; }
        }
    }
    
  • Darin Dimitrov
    Darin Dimitrov about 12 years
    The built-in one is not DataContractSerializer. It is JavaScriptSerializer.
  • bopapa_1979
    bopapa_1979 about 12 years
    Does exactly what I asked. Super simple. Thanks. The new version of Studio is going to ship with JSON.Net as the serializer anyway, so no skin off my back to switch.
  • EBarr
    EBarr about 12 years
    Ya know, I remembered Scott Gu showing pretty-print in a talk about the WebAPI. I went back and scanned the video and couldn't find it, so i didn't mention it. Around minute 36 he starts - channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherla‌​nds/…