我正在使用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"
是任意的;每个阵列都有所不同。
答案 0 :(得分:5)
由于属性名为"testmodule1"
和"testmodule2"
以及"name"
,"admin"
,"path"
,"server"
和"port"
是任意的,事先不知道,您需要将results
数组建模为List<Dictionary<string, Dictionary<string, JsonParametersData>>>
。这是因为,当使用Json.NET将字典序列化为JSON时,字典键将成为JSON属性名称。
因此,可以按如下方式创建上面的JSON:
// Allocate results using collection initializer syntax for the lists and for the dictionaries.
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer
var results = new List<Dictionary<string, Dictionary<string, JsonParametersData>>>()
{
new Dictionary<string, Dictionary<string, JsonParametersData>>()
{
{
"testmodule1",
new Dictionary<string, JsonParametersData>()
{
{
"name",
new JsonParametersData
{
required = true,
options = new List<string>() { "option1", "option2" },
}
},
{
"admin",
new JsonParametersData
{
required = true,
options = new List<string>() { "option1", "option2" },
}
},
{
"path",
new JsonParametersData
{
required = true,
options = new List<string>() { "option1", "option2" },
}
}
}
},
}
};
var moduleName = "testmodule2";
var moduleParameters = new [] { "name", "server", "port" };
// Now add another result, allocating the dictionary with collection initializer syntax also
results.Add(new Dictionary<string, Dictionary<string, JsonParametersData>>()
{
{
moduleName,
// Loop through the parameters and convert them to a dictionary,
// where the parameter name is the key and the corresponding JsonParametersData is the value
moduleParameters
.ToDictionary(n => n,
n => new JsonParametersData
{
required = true,
options = new List<string>() { "option1", "option2" },
})
}
});
var json = JsonConvert.SerializeObject(results, Formatting.Indented);
注意:
有关如何将字典序列化为JSON的文档,请参阅Serialize a Dictionary和Serialization Guide: Dictionaries and Hashtables。
我正在使用collection initializer syntax初始化最外层List<T>
。
我也在使用集合初始化程序语法初始化字典,如How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)所示。
给定一组参数名称以及为每个参数名称获取JsonParametersData
的方法(问题中未显示),LINQ扩展方法Enumerable.ToDictionary<TSource, TKey, TElement>()
可用于构造{来自参数集合的{1}}。
工作样本.Net小提琴here。
答案 1 :(得分:1)
这是使用Newtonsoft JObject的不同方法。
https://dotnetfiddle.net/TdFDQc
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace StackOverflow
{
public class Program
{
public static void Main(string[] args)
{
JArray array = new JArray();
// Module 1
JObject parameter = new JObject();
AddParameter(parameter, "name", true, new[] { "option1", "option2" });
AddParameter(parameter, "admin", true, new[] { "option1", "option2" });
AddParameter(parameter, "path", false, new[] { "option1", "option2", "option3" });
JObject module = new JObject();
module.Add("testmodule1", parameter);
array.Add(module);
// Module 2
parameter = new JObject();
AddParameter(parameter, "name", true, new[] { "option1", "option2" });
AddParameter(parameter, "server", false, Array.Empty<string>());
AddParameter(parameter, "port", true, new[] { "option1", "option2", "option3" });
module = new JObject();
module.Add("testmodule2", parameter);
array.Add(module);
// Display result
var json = array.ToString();
Console.WriteLine(json);
}
static void AddParameter(JObject jObject, string name, bool required, string[] options)
{
JObject parameterProperties = new JObject();
parameterProperties.Add("required", JToken.FromObject(required));
parameterProperties.Add("options", JToken.FromObject(options));
jObject.Add(name, parameterProperties);
}
}
}