如何使用C#创建复杂的JSON字符串?
用Newtonsoft.Json生成目标JSON的简便方案
完全没必要用字符串拼接或正则来生成这类JSON,用Newtonsoft.Json(Json.NET)可以更高效、更可靠地实现,以下是两种常用方式:
方式一:使用字典(适合结构不固定的场景)
如果你的JSON键名是动态变化的,用Dictionary可以灵活构建数据结构:
using Newtonsoft.Json; using System.Collections.Generic; // 构建外层数据容器 var jsonContainer = new Dictionary<string, List<Dictionary<string, string>>>(); // 添加key0对应的数组数据 jsonContainer["key0"] = new List<Dictionary<string, string>> { new() { { "key00", "value00" } }, new() { { "key00", "value01" } } // 按需添加更多元素 }; // 添加key1对应的数组数据 jsonContainer["key1"] = new List<Dictionary<string, string>> { new() { { "key11", "value10" } }, new() { { "key11", "value11" } } // 按需添加更多元素 }; // 序列化为带缩进的格式化JSON string targetJson = JsonConvert.SerializeObject(jsonContainer, Formatting.Indented);
方式二:使用强类型类(适合结构固定的场景)
如果JSON的结构是固定的,定义对应的实体类会让代码可读性更强,且能在编译阶段发现错误:
using Newtonsoft.Json; using System.Collections.Generic; // 定义数组内的元素类 public class Key0Element { public string key00 { get; set; } } public class Key1Element { public string key11 { get; set; } } // 定义外层根对象类 public class RootJson { public List<Key0Element> key0 { get; set; } public List<Key1Element> key1 { get; set; } // 按需添加其他属性 } // 实例化并填充数据 var root = new RootJson { key0 = new List<Key0Element> { new() { key00 = "value00" }, new() { key00 = "value01" } }, key1 = new List<Key1Element> { new() { key11 = "value10" }, new() { key11 = "value11" } } }; // 序列化为格式化JSON string targetJson = JsonConvert.SerializeObject(root, Formatting.Indented);
优势对比
相比字符串拼接和正则,这种方式的好处很明显:
- 自动处理JSON语法细节(比如引号、逗号、特殊字符转义),完全避免手动拼接容易出现的语法错误
- 数据修改更直观,直接操作对象即可,无需修改字符串拼接逻辑
- 代码可读性和可维护性更高,尤其是复杂JSON结构场景
内容的提问来源于stack exchange,提问作者Yarr
相关产品推荐
相关产品推荐

