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

时间:2017-04-25 18:59:26

标签: c# json asp.net-mvc asp.net-mvc-5 json.net

我有一个写在ASP.NET MVC之上的应用程序。在我的一个控制器中,我需要在C#中创建一个对象,所以当它使用JsonConvert.SerializeObject()转换为JSON时,结果看起来像这样

[
  {'one': 'Un'},
  {'two': 'Deux'},
  {'three': 'Trois'}
]

我试图像这样使用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);

但是,上面创建了以下json

{
  'one': 'Un',
  'two': 'Deux',
  'three': 'Trois'
}

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

1 个答案:

答案 0 :(得分:5)

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

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 }});

示例fiddle

相关问题