[英]C# List<string> to JSON objects
I have a list of strings, printing out:我有一个字符串列表,打印出来:
["TEST1","TEST2","TEST3"] [“测试 1”、“测试 2”、“测试 3”]
How would I go about transforming this data to this JSON formatting?我 go 如何将此数据转换为此 JSON 格式?
[ { "value": "TEST1" }, { "value": "TEST2" }, { "value": "TEST3" } ] [{“值”:“TEST1”},{“值”:“TEST2”},{“值”:“TEST3”}]
I do not plan on creating an object.我不打算创建 object。
Have tried using dictionary and key value pairs as well.也尝试过使用字典和键值对。
What about this?那这个呢?
using System;
using System.Linq;
using System.Text.Json;
public class Program
{
public static void Main()
{
var list = new [] {"TEST1","TEST2","TEST3" };
var str = JsonSerializer.Serialize(list.Select(l => new { Value = l }));
Console.WriteLine(str);
}
}
you can try this你可以试试这个
List<string> tests = new List<string> { "TEST1", "TEST2", "TEST3"};
string json = JsonConvert.SerializeObject( tests.Select( t=> new { value = t }));
but I highly recommend to create a class但我强烈建议创建一个 class
string json = JsonConvert.SerializeObject( tests.Select( t => new Test { value = t}));
// or if you are using System.Text.Json
string json = JsonSerializer.Serialize(tests.Select( t=>n ew Test { value = t }));
public class Test
{
public string value {get; set;}
}
json json
[{"value":"TEST1"},{"value":"TEST2"},{"value":"TEST3"}]
Basically the same as the others, but using a foreach
:与其他基本相同,但使用foreach
:
public static string[] TestArray = new[] { "TEST1", "TEST2", "TEST3", };
public static string Test()
{
var data = new List<object>(TestArray.Length);
foreach (var item in TestArray)
{
data.Add(new { @value = item });
}
var result = JsonSerializer.Serialize(data);
return result;
}
Gives:给出:
[
{
"value": "TEST1"
},
{
"value": "TEST2"
},
{
"value": "TEST3"
}
]
It uses System.Text.Json
, but it should get the same result if you use the Newtonsoft serializer.它使用System.Text.Json
,但如果您使用 Newtonsoft 序列化程序,它应该会得到相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.