c# - 如何转换键值对json字符串响应中的字符串列表?

标签 c#

下面是我的字符串列表:

List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });

现在我想以下面的输出形式返回上面的列表到 web 服务:

{
 "element1" : "",
 "element2" : "",
 "element3" : "",
}

我想在我的网站上显示如下输出:

{
 "element1" : "",
 "element2" : "",
 "element3" : "",
}

这就是我现在做的:

 string output = "{" + Environment.NewLine;
            foreach (var item in myList)
            {
                output += $"\"{item}\" : \"\"," + Environment.NewLine;
            }
            output = output.Remove(output.Length - 1) + "}";

但是当我有 40-50 条记录时,我的循环将运行 40-50 次,这是我试图避免的。

我什至尝试过使用这个:

 string output = JsonConvert.SerializeObject(myList); 

但上面没有给出我想要的确切输出格式。

任何人都可以建议我更好的方法来避免 forloop 并减少代码以产生预期的输出吗?

最佳答案

这应该做你想做的事:

string output = JsonConvert.SerializeObject(
                    mylist.ToDictionary(key => key, v => string.Empty));

使用 ToDictionary()我们创建一个 Dictionary<T1, T2> (在你的例子中是 Dictionary<string, string> )从你的列表中。我们正在制作 Key等于列表中的项目,Value只是一个空字符串。

fiddle here

编辑 如果您想要缩进格式,请将第二个参数传递给 SerializeObject:

string output = JsonConvert.SerializeObject(
                    mylist.ToDictionary(key => key, v => string.Empty)
                    Formatting.Indented);

关于c# - 如何转换键值对json字符串响应中的字符串列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45082452/

相关文章:

c# - FontAwesome 未加载到 WebView 中

c# - 在 ASP.NET WebForms NOT MVC 中使用带有 token 的 OAuth 进行 Azure 身份验证

c# - 将 HTML 文件读入内存中的字符串变量

c# - tinyMCE 下拉菜单与 'add hyperlink' 模态断开连接

c# - 从填充到捕捉视觉状态时的首选行为

c# - IIS 7.x,添加启用 HTTPS 的站点 : SiteCollection. Add(string, string, string, byte[]) 重载

c# - 使用 RabbitMQ 的 .NET Core 微服务

c# - 在 C# 文件中包含 C++ 头文件

c# - 将项目添加到 Sitecore 组合框

c# - 通过 HTTP header 模拟用户