如何在.NET中将JSON解析为HTML

3

我正在使用.net的MVC模板,可以显示我的json数据,但现在我想将其解析成html格式,最好是以表格形式呈现,这样更美观。

我将HomeController.cs中获取的json数据传递给了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"}]

在这个页面(About.cshtml)中展示了使用.NET转换为HTML的内容。请注意,保留了HTML标签。
@{
ViewBag.Title = "Evaluaties";
}
<h2>@ViewBag.Title.</h2>
<p>@ViewBag.Message</p>

@Shyju 作为表格会更美观。 - Burst of Ice
我发布了一个回答来做到这一点。 - Shyju
1个回答

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调用后,我反序列化它,在技术上会发生什么? - Burst of Ice
当我复制你的代码时,在FancyPerson处出现了构建错误,它说:“找不到类型或命名空间名称'FancyPerson'”。然而,我已经创建了一个名为FancyPerson的类并将其放在一个新文件夹中,我做错了什么? - Burst of Ice
你创建了一个类还是命名空间?它是否在命名空间下?那么你必须使用 using YourNameSpaceName 来包含该命名空间,或者使用完全限定名称,如 YourNameSpaceName.YourClassName - Shyju
我把它放在这里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; } } } - Burst of Ice
那么,要么您必须在使用此类的其他地方(例如:您的控制器)中使用“using ASPNetMVCExtendingIdentity2Roles.Domain;”,要么使用完全限定名称“ASPNetMVCExtendingIdentity2Roles.Domain.FancyPerson”。 - Shyju
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接