在ASP.NET MVC的视图中显示格式化的JSON

时间:2012-10-02 16:40:52

标签: css xml asp.net-mvc json razor

有没有办法格式化JSON以在视图中显示?这样当我添加新属性时,我的API文档会自动更新?额外的功劳是用CSS包围某些元素来设计它。我也想为XML做这件事。

class Student 
{
      static CreateEmpty()
      {
           return new Student() {
                 FirstName: 'Mike',
                 LastName: 'Flynn',
                 Classes: new List<Class>(),
                 School: new School() {
                      Name: 'High School'
                 }
           }
      }
}


<code>
@(Student.CreateEmpty().ToJSON())
</code>

<code>

{
     FirstName: 'Mike',
     LastName: 'Flynn',
     Classes: [],
     School: {
          Name: 'High School'
     }
}

</code>

3 个答案:

答案 0 :(得分:18)

您可以使用支持的JSON.NET来控制JSON格式并缩进它:

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

答案 1 :(得分:1)

另一种使用 Newtonsoft 的方式。请注意,pre html 标记对于保持格式很重要。

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

答案 2 :(得分:0)

我的解决方案是直接格式化HTML(用于调试目的) 你可以把它变得更加漂亮。

    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>&nbsp;:&nbsp;");
                FormatJSONObject(v.Value, sb, indent + 2);
            }
            sb.AppendLine("</div>}<br>");
        }
        else
        {
            sb.Append(o.ToString());
            sb.AppendLine("<br>");
        }
    }

然后在我的ASP服务器侧面按钮点击处理程序...

    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>&nbsp;" + 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>&nbsp;" + 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>&nbsp;" + response.StatusCode.ToString();
            }

        }
    }