如何在C#中创建键/值对数组?

Jay*_*len 4 c# asp.net-mvc json json.net asp.net-mvc-5

我有一个在ASP.NET MVC之上编写的应用程序。在我的一个控制器中,我需要在C#中创建一个对象,因此当使用JsonConvert.SerializeObject()结果将其转换为JSON时,如下所示

[
  {'one': 'Un'},
  {'two': 'Deux'},
  {'three': 'Trois'}
]
Run Code Online (Sandbox Code Playgroud)

我试图用Dictionary<string, string>这样

var opts = new Dictionary<string, string>();
opts.Add("one", "Un");
opts.Add("two", "Deux");
opts.Add("three", "Trois");

var json = JsonConvert.SerializeObject(opts);
Run Code Online (Sandbox Code Playgroud)

但是,上面创建了以下json

{
  'one': 'Un',
  'two': 'Deux',
  'three': 'Trois'
}
Run Code Online (Sandbox Code Playgroud)

如何以某种方式创建对象以JsonConvert.SerializeObject()生成所需的输出?

dbc*_*dbc 6

您的外部JSON容器是一个array,因此您需要List<Dictionary<string, string>>为根对象返回某种非字典式集合,例如a ,如下所示:

var opts = new Dictionary<string, string>();
opts.Add("one", "Un");
opts.Add("two", "Deux");
opts.Add("three", "Trois");

var list = opts.Select(p => new Dictionary<string, string>() { {p.Key, p.Value }});
Run Code Online (Sandbox Code Playgroud)

样品提琴