Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 476
Jaylen Avatar asked Apr 25 '17 18:04

Jaylen


People also ask

What is key-value in array in C?

C does not have a data structure of this type; in fact, the only collection type you have built in to C is the array. So, if you want something where you can supply a key and get the value, you have to roll your own or find one on the Internet.

How do you create a key-value pair?

To add key-value pair in C# Dictionary, firstly declare a Dictionary. IDictionary<int, string> d = new Dictionary<int, string>(); Now, add elements with KeyValuePair. d.

Do arrays use key value pairs?

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.


Video Answer


1 Answers

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.

like image 136
dbc Avatar answered Oct 01 '22 21:10

dbc