【问题标题】:How to enumerate json string in MVC Razor foreach loop?如何在 MVC Razor foreach 循环中枚举 json 字符串?
【发布时间】:2016-08-13 01:19:05
【问题描述】:

我正在使用 SQL Server 2016 在我的数据集中的字符串字段中返回 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}]

最好的方法是什么?

【问题讨论】:

  • 我的猜测是必须将对象转换为数组或其他东西。您可能还必须将每个项目转换为其他项目。为什么不想使用 JSON.Net 将其转换为对象?
  • 所以你在Model.AccountSettings.EmailNotifications 中有一个EmailNotification 类对象的列表?还是只是一个字符串?你的字符串值是什么样子的?
  • 是的,它只是一个字符串
  • Eonasdan - 有没有办法在不创建对象和序列化的情况下做到这一点?
  • 你也可以使用FastJson

标签: json asp.net-mvc razor foreach enumeration


【解决方案1】:

干净的解决方案是创建一个类来表示 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>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多