在C#中,对象与JSON互转最常用、最推荐的方式是使用 System.Text.Json(.NET Core 3.0+ 内置,无需额外安装),它性能好、安全、轻量。如果项目还在用 .NET Framework 或需要更多功能(比如支持字段、循环引用、自定义转换器更灵活),也可以用 Newtonsoft.Json(即 Json.NET)。
用 System.Text.Json 序列化对象为 JSON
这是现代 C# 的首选方式,简单高效:
确保 using System.Text.Json; 调用 JsonSerializer.Serialize(obj) 即可转成 JSON 字符串 支持选项配置,比如格式化输出、忽略 null 值、处理大小写示例:
var person = new { Name = "张三", Age = 28 };
string json = JsonSerializer.Serialize(person, new JsonSerializerOptions
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
});输出:
{
"Name": "张三",
"Age": 28
}
用 System.Text.Json 反序列化 JSON 为对象
把 JSON 字符串还原成 C# 对象(需有匹配的类型或用匿名/动态类型):
用 JsonSerializer.Deserialize示例:
string json = @"{""name"":""李四"",""age"":30}";
var person = JsonSerializer.Deserialize<Person>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});用 Newtonsoft.Json(Json.NET)做互转(兼容老项目)
需通过 NuGet 安装 Newtonsoft.Json 包。它的 API 更灵活,历史生态更广:
序列化:JsonConvert.SerializeObject(obj, Formatting.Indented) 反序列化:JsonConvert.DeserializeObject示例:
var user = new User { UserName = "admin", CreatedAt = DateTime.Now };
string json = JsonConvert.SerializeObject(user, Formatting.Indented);注意事项和常见问题
无论用哪个库,都需要注意:
对象属性必须是 public,否则默认不参与序列化(Newtonsoft 可配) DateTime 默认序列化为 ISO 8601 字符串,如需自定义格式,要配置转换器 含循环引用的对象(如父子关系)会报错,需启用相应选项(Newtonsoft 支持 ReferenceLoopHandling.Ignore) 反序列化时类型不匹配会抛异常,建议加 try-catch 或用 TryDeserialize(.NET 7+ 提供) 敏感字段可用 [JsonIgnore] 或 JsonSerializerOptions.DefaultIgnoreCondition 排除基本上就这些。选 System.Text.Json 是新项目的标准做法;已有项目重度依赖 Newtonsoft,也没必要强行替换。
