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
我有一个在ASP.NET MVC上编写的应用程序。在我的一个控制器中,我需要在C#中创建一个对象,所以当它使用JsonConvert.SerializeObject()转换为JSON时,结果看起来像这样
[
{'one': 'Un'},
{'two': 'Deux'},
{'three': 'Trois'}
]
I tried to use Dictionary<string, string>
like this
我试着像这样使用Dictionary
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
但是,上面创建了以下json
{
'one': 'Un',
'two': 'Deux',
'three': 'Trois'
}
How can I create the object in a way so that JsonConvert.SerializeObject()
generate the desired output?
如何以某种方式创建对象,以便JsonConvert.SerializeObject()生成所需的输出?
1 个解决方案
#1
4
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:
您的外部JSON容器是一个数组,因此您需要为根对象返回某种非字典集合,例如List
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.
#1
4
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:
您的外部JSON容器是一个数组,因此您需要为根对象返回某种非字典集合,例如List
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.