如何将C# List<string>转换为指定格式的JSON对象?
无需实体类实现List转指定格式JSON
你可以通过匿名类型或者字典集合的方式实现,下面是两种常用JSON库的具体实现:
方法一:使用Newtonsoft.Json(Json.NET)
如果项目中已经引用了Newtonsoft.Json包,直接用LINQ将原列表映射为匿名对象集合再序列化:
using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; // 原字符串列表 var stringList = new List<string> { "TEST1", "TEST2", "TEST3" }; // 将每个字符串转换为带value属性的匿名对象 var targetCollection = stringList.Select(str => new { value = str }); // 序列化为带缩进的JSON var jsonResult = JsonConvert.SerializeObject(targetCollection, Formatting.Indented);
方法二:使用System.Text.Json(.NET Core/.NET 5+ 内置)
如果用的是较新版本的.NET,直接用内置的序列化工具:
using System.Collections.Generic; using System.Linq; using System.Text.Json; // 原字符串列表 var stringList = new List<string> { "TEST1", "TEST2", "TEST3" }; // 映射为匿名对象集合 var targetCollection = stringList.Select(str => new { value = str }); // 设置序列化选项(缩进格式化) var serializeOptions = new JsonSerializerOptions { WriteIndented = true }; // 生成JSON var jsonResult = JsonSerializer.Serialize(targetCollection, serializeOptions);
补充:用字典集合实现
你提到已经尝试过字典方式,可能是写法问题。正确的做法是为每个字符串单独创建一个仅包含"value"键的字典,再序列化这个字典集合:
// 以Newtonsoft.Json为例,System.Text.Json写法类似 var targetCollection = stringList.Select(str => new Dictionary<string, string> { { "value", str } }); var jsonResult = JsonConvert.SerializeObject(targetCollection, Formatting.Indented);
以上几种方式都不需要定义实体类,最终都会生成你需要的JSON格式。
内容的提问来源于stack exchange,提问作者kngovanduc
相关产品推荐
相关产品推荐

