2016-08-12 87 views
0

我正在使用SQL Server 2016在我的数据集中的字符串字段中返回json数据。我没有任何转换就将json字符串传递给模型。我想列举我的JSON字符串场MVC剃刀一样:如何在MVC Razor foreach循环中枚举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}] 

要做到这一点的最佳方法是什么?

+0

我的猜测是,将不得不把对象作为数组或东西。您可能还必须将每个项目投到其他项目。你为什么不想使用JSON.Net将其转换为对象? – Eonasdan

+0

因此,您有'Model.AccountSettings.EmailNotifications'中的'EmailNotification'类对象列表?或者它只是一个STRING?你的字符串值是怎样的? – Shyju

+0

是的,它只是一个字符串 – Rodney

回答

2

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

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> 
}