【发布时间】:2018-10-25 21:22:40
【问题描述】:
我正在网络抓取一些数据并尝试使用 c# newtonsoft.Json 将抓取的数据写入 json 文件。
将数据写入 控制器 中的 Json 文件时,我遇到了问题。 c# 中的多维数组让我很困惑。
提前致谢。
这是我尝试创建的 Json 文件的示例:
[
{
"testmodule1": {
"name": {
"required": true,
"options": [
"option1",
"option2"
]
},
"admin": {
"required": true,
"options": [
"option1",
"option2"
]
},
"path": {
"required": true,
"options": [
"option1",
"option2"
]
}
}
},
{
"testmodule2": {
"name": {
"required": true,
"options": [
"option1",
"option2"
]
},
"server": {
"required": false,
"options": [
]
},
"port": {
"required": true,
"options": [
"option1",
"option2"
]
}
}
}
]
这些是我的课程:
public class JsonData
{
public Dictionary<string, JsonParameters> modulename { get; set; }
}
public class JsonParameters
{
public JsonParametersData parameter { get; set; }
}
public class JsonParametersData
{
public bool required { get; set; }
public List<string> options { get; set; }
}
这是我的控制器,这是我卡住的地方。 名称 modulename 在当前上下文中不存在:
public class WebscrapeController : Controller
{
// GET: Webscrape
public ActionResult Index()
{
List<JsonData> data = new List<JsonData>();
data.Add(new JsonData()
{
modulename = new Dictionary<string, JsonParameters>()
{
modulename.Add("testmodule1", new JsonParameters()
{
parameter = new JsonParametersData()
{
required = true,
options = new List<string>()
{
"option1",
"option2"
}
}
})
}
});
string json = JsonConvert.SerializeObject(data.ToArray());
//write string to file
System.IO.File.WriteAllText(
@"C:mypath",
json);
}
}
注意属性名称"testmodule1"和"testmodule2"以及"name"、"admin"、"path"、"server"是任意的;它们因每个数组而异。
【问题讨论】:
-
多维数组在哪里?什么不起作用?
-
1) 名称
"testmodule1"和"testmodule2"是预先确定的还是任意的? 2) 名称"name"、"admin"、"path"、"server"和"port"是预先确定的还是任意的? -
任意,每个数组都不一样
-
我填充 json 数组的方式不起作用。
标签: c# asp.net arrays json web-scraping