10

有没有办法格式化 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>
4

3 回答 3

28

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

<pre>
    @Html.Raw(JsonConvert.SerializeObject(Student.CreateEmpty(), Formatting.Indented))
</pre>
于 2012-10-02T16:50:05.417 回答
1

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

<pre>
@Html.Raw(Newtonsoft.Json.Linq.JValue.Parse(Student.CreateEmpty()).ToString(Newtonsoft.Json.Formatting.Indented)
</pre>
于 2021-01-20T20:49:14.077 回答
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();
            }

        }
    }
于 2016-03-18T19:50:34.153 回答