C# 将字符串列表转换为json格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17865584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:40:59  来源:igfitidea点击:

Convert a list of string into json format

c#asp.netjson

提问by Sachin Prasad

How to convert a list of string

如何转换字符串列表

 List<string> keys = new List<string>() { "1-12VEXP", "1-124DH9"};

To json format same as :

到 json 格式相同的:

[["1-12VEXP"],["1-124DH9"]] 

in .net.

在.net中。

I'm using Newtonsoft.Json .

我正在使用 Newtonsoft.Json 。

Any help will be greatly appreciated.

任何帮助将不胜感激。

采纳答案by Joe Enos

Straight-up serialization won't work, since the items are not equivalent. If you truly want what you're asking for, then you need an array which contains arrays, then serialize that array:

直接序列化将不起作用,因为项目不等价。如果你真的想要你想要的东西,那么你需要一个包含数组的数组,然后序列化该数组:

You can do that by first converting your collection, then simple JSON serialization:

您可以通过首先转换您的集合,然后进行简单的 JSON 序列化来做到这一点:

string[][] newKeys = keys.Select(x => new string[]{x}).ToArray();

string json = JsonConvert.SerializeObject(newKeys);

回答by Amy

With Newtonsoft.Json:

使用 Newtonsoft.Json:

JsonConvert.SerializeObject(keys);

will give you JSON.

会给你 JSON。