How to create array of key/value pair in c#?

心已入冬 提交于 2019-12-10 09:24:18

问题


I have an application that is written on top of ASP.NET MVC. In one of my controllers, I need to create an object in C# so when it is converted to JSON using JsonConvert.SerializeObject() the results looks like this

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

I tried to use Dictionary<string, string> like this

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

var json = JsonConvert.SerializeObject(opts);

However, the above creates the following json

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

How can I create the object in a way so that JsonConvert.SerializeObject() generate the desired output?


回答1:


Your outer JSON container is an array, so you need to return some sort of non-dictionary collection such as a List<Dictionary<string, string>> for your root object, like so:

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

Sample fiddle.



来源:https://stackoverflow.com/questions/43618859/how-to-create-array-of-key-value-pair-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!