I am trying to deserialize my JSON with Newtonsoft's Json.NET so I can loop through it with an foreach
loop.
I know that I have to model my class as my JSON object and I think this is where I come up short.
Also I am not quite sure how to implement the namespace so I basically just put it underneath the @page which doesn't throw and error so I guess that's fine (if this is wrong please let me know).
My files are:
TodoItem.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1
{
public class TodoItem
{
public List<Array> tasks { get; set; }
public int id { get; set; }
public string name{ get; set; }
}
}
Tasks.json:
[
{
"tasks": [
{
"id": 1,
"name": "Køb tøj"
},
{
"id": 2,
"name": "vask tøj"
},
{
"id": 3,
"name": "Gør Rent"
}
]
}
]
Index.cshtml:
@using WebApplication1
@{
Layout = "_Layout.cshtml";
var json = System.IO.File.ReadAllText("pathtojson");
List<TodoItem> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TodoItem>>(json);
}
@{
foreach(var item in data)
{
<p>@item</p>
}
}
You have an collection of Tasks
. Each Task
has Id
and Name
properties.
This can be modelled by splitting your class and updating to the below:
public class TodoItem
{
public List<Task> Tasks { get; set; }
}
public class Task
{
public int Id { get; set; }
public string Name { get; set; }
}
Then you can deserialize as:
TodoItem data = JsonConvert.DeserializeObject<TodoItem>(json);
foreach (var task in data.Tasks)
{
Console.WriteLine($"Id: {task.Id}, Name: {task.Name}");
}
Rather than process the json in the view, I would deserialize the json in the controller then pass the deserialized json (model) back to the view.
// controller
public IActionResult Index()
{
var json = System.IO.File.ReadAllText("pathtojson");
TodoItem data = JsonConvert.DeserializeObject<TodoItem>(json);
return View(data); // pass the data the your view
}
// razor view
@model WebApplication1.Models.TodoItem // define model for view
@{
Layout = "_Layout.cshtml";
}
@foreach (var task in Model.Tasks)
{
<div>Id: @task.Id, Name: @task.Name</div>
}
I created a fiddle.