【发布时间】:2019-09-30 18:18:46
【问题描述】:
我正在尝试使用 newtonsoftjson 反序列化我的 JSON,因此我无法使用 foreach 循环遍历它。
我知道我必须将我的类建模为我的 JSON 对象,我认为这是我的不足之处。
另外我不太确定如何实现命名空间,所以我基本上只是将它放在不会抛出错误的@page 下面,所以我想这很好(如果这是错误的,请告诉我)。
我的文件是:
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>
}
}
【问题讨论】:
-
好的所以我自己想通了,但是感谢您查看我的代码。我的解决方案是我拆分我的代码。所以我有一个任务集合和一个待办事项,所以它完全反映了我的 json 格式。
标签: c# json asp.net-core razor