如何在 MVC Razor foreach 循环中枚举 json 字符串?

How to enumerate json string in MVC Razor foreach loop?

我正在使用 SQL Server 2016 来 return json 我数据集中字符串字段中的数据。我将 json 字符串传递给了模型,没有进行任何转换。我想在 MVC razor 中枚举我的 json 字符串字段,例如:

 @foreach (var notification in Model.AccountSettings.EmailNotifications)
 {

EmailNotifications 是一个 json 对象数组。

EmailNotifications = [{"EmailNotificationID":8,"EmailNotificationName":"Any new KLAS report is published.","IsSet":false},{"EmailNotificationID":9,"EmailNotificationName":"KLAS publishes a report in one of my areas of interest.","IsSet":false}]

最好的方法是什么?

干净的解决方案是创建一个 class 来表示 JSON 数组中的每个项目,将您的字符串转换为这个 class 的列表并枚举那个。

public class NotificationItem
{
    public int EmailNotificationID { get; set; }
    public string EmailNotificationName { get; set; }
    public bool IsSet { get; set; }
}

并且您可以使用 Newtonsoft.Json.JsonConvert.DeserializeObject 方法将 json 字符串转换为 NotificationItem 对象列表。

@{
    var items = Newtonsoft.Json.JsonConvert
                .DeserializeObject<List<NotificationItem>>("yourJsonStringHere");
}
@foreach (var item in items)
{
    <p>@item.EmailNotificationID</p>
    <p>@item.EmailNotificationName </p>
}