0

I'm using SQL Server 2016 to return json data in a string field in my data set. I passed the json string to the model without any conversions. I want to enumerate my json string field in MVC razor like:

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

EmailNotifications is a json array of objects.

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

What the best way to do this?

Rodney Hickman
  • 3,133
  • 11
  • 53
  • 83

1 Answers1

2

The clean solution is to create a class to represent each item in your JSON array, convert your string to a list of this class and enumerate that.

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

And you may use Newtonsoft.Json.JsonConvert.DeserializeObject method to convert the json string to list of NotificationItem objects.

@{
    var items = Newtonsoft.Json.JsonConvert
                .DeserializeObject<List<NotificationItem>>("yourJsonStringHere");
}
@foreach (var item in items)
{
    <p>@item.EmailNotificationID</p>
    <p>@item.EmailNotificationName </p>
}
Shyju
  • 214,206
  • 104
  • 411
  • 497