7

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?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Jaylen
  • 39,043
  • 40
  • 128
  • 221
  • 1
    Try an array of KeyValue pairs? – RBarryYoung Apr 25 '17 at 19:05
  • 1
    Possible duplicate of [Json.Net - Serialize Dictionary as Array (of Key Value Pairs)](http://stackoverflow.com/questions/12751354/json-net-serialize-dictionary-as-array-of-key-value-pairs) – krillgar Apr 25 '17 at 19:05
  • 1
    @krillgar - it's not quite a duplicate. In that question the dictionary entry property names are fixed as `"k"` and `"v"` but the question wants the property names to be the dictionary key values. – dbc Apr 25 '17 at 19:15

1 Answers1

10

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.

dbc
  • 104,963
  • 20
  • 228
  • 340