有没有一种方法可以格式化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>发布于 2012-10-03 00:50:05
您可以使用支持的JSON.NET来控制JSON格式并对其进行缩进:
<pre>
@Html.Raw(JsonConvert.SerializeObject(Student.CreateEmpty(), Formatting.Indented))
</pre>发布于 2021-01-21 04:49:14
使用Newtonsoft的另一种方式。请注意,pre html标记对于保持格式很重要。
<pre>
@Html.Raw(Newtonsoft.Json.Linq.JValue.Parse(Student.CreateEmpty()).ToString(Newtonsoft.Json.Formatting.Indented)
</pre>发布于 2016-03-19 03:50:34
我的解决方案就是直接格式化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> : ");
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> " + 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();
}
}
}https://stackoverflow.com/questions/12694571
复制相似问题