Get Prettified JSON from MVC 3 JsonResult
Asked Answered
C

2

6

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; }
    }
}
Chalcidice answered 27/3, 2012 at 22:52 Comment(3)
What about using a browser-extension (e.g. addons.mozilla.org/en-US/firefox/addon/jsonview) which automatically prettifies application/json content?Pliant
Both Chrome's built-in dev tool and Firebug now have a preview mode that automatically gives you a nice hierarchical view of JSON returned from the server.Basham
Hey guys. Thanks for all the great responses. I also found a Visual Studio Visualizer that lets you format JSON within Visual Studio. I have toyed with it a bit, and have it working in Studio 2010. jsonviewer.codeplex.com/…Chalcidice
E
16

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/

Ensheathe answered 27/3, 2012 at 23:20 Comment(3)
The built-in one is not DataContractSerializer. It is JavaScriptSerializer.Postmistress
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.Chalcidice
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-Netherlands/…Ensheathe
I
4

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.

Intrigante answered 28/3, 2012 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.