Display formatted JSON in the view in ASP.NET MVC Display formatted JSON in the view in ASP.NET MVC xml xml

Display formatted JSON in the view in ASP.NET MVC


You could use JSON.NET which supports to control the JSON format and indent it:

<pre>    @Html.Raw(JsonConvert.SerializeObject(Student.CreateEmpty(), Formatting.Indented))</pre>


An other way using Newtonsoft. Note the pre html tag is important to maintain the format.

<pre>@Html.Raw(Newtonsoft.Json.Linq.JValue.Parse(Student.CreateEmpty()).ToString(Newtonsoft.Json.Formatting.Indented)</pre>


My solution is just formatting HTML directly (for debug purposes)You could make this much fancier.

    public static void FormatJSONObject(object o, StringBuilder sb, int indent)    {        if(o.GetType() == typeof(System.Object[]))        {            sb.AppendLine("[<br>");            int idx = 0;            foreach(object obj in (object[])o)            {                sb.Append("<b><i>" + idx + "</i></b><br><div style='padding-left: " + indent + "em;'>");                FormatJSONObject(obj, sb, indent + 2);                sb.AppendLine("</div>");                idx++;            }            sb.AppendLine("]<br>");        }        else if(o.GetType() == typeof(Dictionary<string, object>))        {            sb.AppendLine("{<br><div style='padding-left: " + indent + "em;'>");            foreach (var v in (Dictionary<string, object>)o)            {                sb.Append("<b>");                sb.Append(v.Key);                sb.Append("</b> : ");                FormatJSONObject(v.Value, sb, indent + 2);            }            sb.AppendLine("</div>}<br>");        }        else        {            sb.Append(o.ToString());            sb.AppendLine("<br>");        }    }

Then called in my ASP server side button click handler...

    protected  void GoButton_Click(object sender, EventArgs e)    {        RegisterAsyncTask(new PageAsyncTask(LoadTestData));    }    public async Task LoadTestData()    {        using (HttpClient client = new HttpClient())        {            // Like "http://jsonplaceholder.typicode.com"            client.BaseAddress = new Uri(APIURLBase.Text);            client.DefaultRequestHeaders.Accept.Clear();            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));            // Like "posts/1"            HttpResponseMessage response = await client.GetAsync(APIURLRequest.Text);            if (response.IsSuccessStatusCode)            {                StringBuilder sb = new StringBuilder();                sb.AppendLine("<H1>Return Status:</H1> " + response.StatusCode.ToString() + "<br>");                sb.AppendLine("<H1>Headers</H1><br>");                foreach (var h in response.Headers)                {                    foreach (var v in h.Value)                    {                        sb.AppendLine("<label>" + h.Key + "</label> " + v + "<br>");                    }                }                sb.AppendLine("<H1>Content</H1><br>");                sb.AppendLine("<label>Content Type: </label>" + Response.ContentType + "<br>");                Stream memStream = new MemoryStream();                Stream bodyStream = await response.Content.ReadAsStreamAsync();                bodyStream.CopyTo(memStream);                memStream.Position = 0;                using (StreamReader reader = new StreamReader(memStream))                {                    string body = reader.ReadToEnd();                    if (ShowRawContentCB.Checked)                    {                        sb.AppendLine(body + "<br>");                    }                    else                    {                        JavaScriptSerializer ser = new JavaScriptSerializer();                        object o = ser.Deserialize(body, typeof(object));                        FormatJSONObject(o, sb);                    }                }                this.results.InnerHtml = sb.ToString();            }            else            {                this.results.InnerHtml = "<label>Error:</label> " + response.StatusCode.ToString();            }        }    }