【问题标题】:How to parse json to html in .net如何在.net中将json解析为html
【发布时间】:2016-08-24 15:59:29
【问题描述】:

我正在使用来自 .net 的 MVC 模板,我可以显示我的 json,但现在我想将其解析为 html,最好是在表格中,这样看起来会更好。

我从 HomeController.cs 获取 json 到我的 View,即 About.cshtml,但它只是 json 字符串,所以看起来很糟糕。

public class HomeController : Controller
{
    public JsonResult TestJson()
    {
        var client = new WebClient();
        var response = client.DownloadString(new Uri("http://localhost:8080/projecten/api/leerlingen"));

        var someObject = JsonConvert.DeserializeObject(response);

        return new JsonResult() { Data = someObject, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

    public ActionResult About()
    {
        var client = new WebClient();
        var json = client.DownloadString(new Uri("http://localhost:8080/projecten/api/leerlingen"));
        //parse json
        ViewBag.Message = json;
        return View();
    }
}

这是json

[{"inschrijvingsNummer":"0001","naam":"John Smith","email":"john.smith@example.com","evaluatieNummer":"270"},
{"inschrijvingsNummer":"0002","naam":"Joe Bloggs","email":"joe.bloggs@example.com","evaluatieNummer":"370"}]

使用 .net 转换为 html 我在此页面中显示 (About.cshtml)

@{
ViewBag.Title = "Evaluaties";
}
<h2>@ViewBag.Title.</h2>
<p>@ViewBag.Message</p>

【问题讨论】:

  • @Shyju 作为桌子会更好看
  • 我发布了一个答案。

标签: c# html .net json asp.net-mvc


【解决方案1】:

您基本上应该创建一个代表 json 数组中数据的类。

public class FancyPerson
{
    public string InschrijvingsNummer { get; set; }
    public string Naam { get; set; }
    public string Email { get; set; }
    public string EvaluatieNummer { get; set; }
}

当您从 http 调用中获取 json 字符串(其中包含一个项目数组)时,将其反序列化为此类的集合。

var items = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<FancyPerson>>(json);
ViewBag.Message = items;

现在在您看来,您只需要将这个 ViewBag 项目转换为 FancyPerson 对象的列表。您可以遍历项目并将其显示在表格行中。

@{
    var items = (List<FancyPerson>) ViewBag.Message;
}
<table>
@foreach (var item in items)
{
    <tr>
        <td>@item.Naam</td>
        <td>@item.Email</td>
    </tr>
}
</table>

【讨论】:

  • 感谢您的帮助。我在哪里放置 FancyPerson 类?所以我在进行http调用后反序列化它,这究竟是做什么的?
  • 你可以把它放在你项目的任何地方。您的 http 调用基本上返回一个字符串(其中包含字符串格式的项目数组)。 Desirialize 方法会将数组中的项目转换为此类的单个对象。
  • 当我复制你的代码时,它在 FancyPerson 上给出了一个构建错误,它说:找不到类型或命名空间名称“FancyPerson”。然而创建了一个名为 FancyPerson 的类并将其放在一个新文件夹中,我做错了什么?
  • 你创建了类还是命名空间?它在命名空间下吗?然后,您必须使用 using YourNameSpaceName 包含该命名空间或使用完全限定名称,例如 YourNameSpaceName.YourClassName
  • 我把它放在这里namespace ASPNetMVCExtendingIdentity2Roles.Domain { public class FancyPerson { public string InschrijvingsNummer { get; set; } public string Naam { get; set; } public string Email { get; set; } public string EvaluatieNummer { get; set; } } }
猜你喜欢
  • 2021-12-26
  • 2010-12-31
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2020-06-14
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多