使用C# Newtonsoft.Json写入JSON文件遇多维数组问题求助
解决C# Newtonsoft.Json生成目标JSON的错误与结构问题
首先,你遇到的**"modulename在当前上下文中不存在"**错误,根源是在对象初始化器中直接调用modulename.Add(...)——此时modulename还没完成初始化,编译器无法识别这个变量。除此之外,你的自定义类结构和目标JSON的格式不匹配,这也是无法生成正确JSON的核心问题,我来一步步帮你修正。
1. 修正自定义类结构
你的目标JSON没有多余的嵌套层级(比如parameter或modulename节点),所以需要重新定义类来匹配JSON的结构:
// 对应每个参数的required和options属性 public class ParameterDetail { public bool required { get; set; } public List<string> options { get; set; } }
不需要原来的JsonData和JsonParameters类,因为我们可以直接用List<Dictionary<string, Dictionary<string, ParameterDetail>>>来对应顶级数组的结构:
- 顶级是一个
List(对应JSON数组) - 每个List元素是一个
Dictionary<string, ...>(对应JSON中单个模块的对象,键是模块名如testmodule1) - 字典的值是另一个
Dictionary<string, ParameterDetail>(对应模块下的参数集合,键是参数名如name,值是参数详情)
2. 修正Controller中的代码(解决初始化错误)
把原来错误的初始化方式改成集合初始化器语法,同时按照正确的结构组装数据:
public class WebscrapeController : Controller { // GET: Webscrape public ActionResult Index() { // 初始化顶级列表,对应目标JSON的数组 List<Dictionary<string, Dictionary<string, ParameterDetail>>> data = new List<Dictionary<string, Dictionary<string, ParameterDetail>>>(); // 添加第一个模块testmodule1 data.Add(new Dictionary<string, Dictionary<string, ParameterDetail>>() { { "testmodule1", new Dictionary<string, ParameterDetail>() { { "name", new ParameterDetail() { required = true, options = new List<string> { "option1", "option2" } } }, { "admin", new ParameterDetail() { required = true, options = new List<string> { "option1", "option2" } } }, { "path", new ParameterDetail() { required = true, options = new List<string> { "option1", "option2" } } } } } }); // 添加第二个模块testmodule2 data.Add(new Dictionary<string, Dictionary<string, ParameterDetail>>() { { "testmodule2", new Dictionary<string, ParameterDetail>() { { "name", new ParameterDetail() { required = true, options = new List<string> { "option1", "option2" } } }, { "server", new ParameterDetail() { required = false, options = new List<string>() } }, { "port", new ParameterDetail() { required = true, options = new List<string> { "option1", "option2" } } } } } }); // 序列化为JSON,加Formatting.Indented可以生成格式化的JSON,方便调试 string json = JsonConvert.SerializeObject(data, Formatting.Indented); // 注意路径要写正确,比如加上文件名@"C:\mypath\output.json" System.IO.File.WriteAllText(@"C:\mypath\output.json", json); return View(); } }
3. 为什么原来的代码会出错?
- 初始化错误:你在
new Dictionary<...>()的初始化器里用了modulename.Add(...),但此时modulename是JsonData的属性,还没被赋值,编译器找不到这个变量。正确的做法是用集合初始化器的{ key, value }语法来添加字典项。 - 类结构不匹配:原来的
JsonParameters类多了一层parameter属性,会导致生成的JSON多出不必要的嵌套节点,完全不符合你想要的目标格式。
运行修正后的代码,就能生成和你示例完全一致的JSON文件了。
内容的提问来源于stack exchange,提问作者ChakirBelhaj
相关产品推荐
相关产品推荐

