How to create an array of key / value pairs in C #?

I have an application 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 look like

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

I tried using 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 an object in such a way as to JsonConvert.SerializeObject()generate the desired result?

+4
source share
1 answer

JSON , - -, ​​ 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.

+4

Source: https://habr.com/ru/post/1675644/


All Articles