如何在C#中创建键/值对数组? [英] How to create array of key/value pair in c#?

查看:243
本文介绍了如何在C#中创建键/值对数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在ASP.NET MVC之上编写的应用程序.在我的一个控制器中,我需要在C#中创建一个对象,因此当使用JsonConvert.SerializeObject()将其转换为JSON时,结果看起来像这样

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'}
]

我试图这样使用Dictionary<string, string>

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

var json = JsonConvert.SerializeObject(opts);

但是,上面的代码创建了以下json

However, the above creates the following json

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

如何创建对象以使JsonConvert.SerializeObject()生成所需的输出?

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

推荐答案

您的外部JSON容器是数组,因此您需要为根对象返回某种非词典集合,例如List<Dictionary<string, string>>,例如:

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

示例小提琴.

这篇关于如何在C#中创建键/值对数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆