【问题标题】:How to create array of key/value pair in c#?如何在 C# 中创建键/值对数组?
【发布时间】:2017-09-22 22:49:49
【问题描述】:

我有一个基于 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() 生成所需的输出?

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多