.NET 对象转Json的方式

.NET 对象转Json的方式

在.NET中将对象转换为JSON有多种方法,以下是常用的几种方式:

1. 使用 System.Text.Json (推荐,.NET Core 3.0+)

基本序列化

csharp 复制代码
using System.Text.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

// 对象转JSON
var person = new Person { Name = "张三", Age = 25, Email = "zhangsan@example.com" };
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine(jsonString);
// 输出: {"Name":"张三","Age":25,"Email":"zhangsan@example.com"}

带选项的序列化

csharp 复制代码
var options = new JsonSerializerOptions
{
    WriteIndented = true, // 格式化输出
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase // 驼峰命名
};

string jsonString = JsonSerializer.Serialize(person, options);
Console.WriteLine(jsonString);
// 输出:
// {
//   "name": "张三",
//   "age": 25,
//   "email": "zhangsan@example.com"
// }

2. 使用 Newtonsoft.Json (Json.NET)

首先安装 NuGet 包:

复制代码
Install-Package Newtonsoft.Json
csharp 复制代码
using Newtonsoft.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

// 基本序列化
var person = new Person { Name = "李四", Age = 30, Email = "lisi@example.com" };
string jsonString = JsonConvert.SerializeObject(person);
Console.WriteLine(jsonString);

// 带格式的序列化
string formattedJson = JsonConvert.SerializeObject(person, Formatting.Indented);
Console.WriteLine(formattedJson);

Newtonsoft.Json 高级用法

csharp 复制代码
var settings = new JsonSerializerSettings
{
    Formatting = Formatting.Indented,
    NullValueHandling = NullValueHandling.Ignore,
    DateFormatString = "yyyy-MM-dd HH:mm:ss"
};

string jsonString = JsonConvert.SerializeObject(person, settings);

3. 处理复杂对象

包含集合的对象

csharp 复制代码
public class Department
{
    public string Name { get; set; }
    public List<Person> Employees { get; set; }
}

var department = new Department
{
    Name = "技术部",
    Employees = new List<Person>
    {
        new Person { Name = "王五", Age = 28, Email = "wangwu@example.com" },
        new Person { Name = "赵六", Age = 32, Email = "zhaoliu@example.com" }
    }
};

string jsonString = JsonSerializer.Serialize(department, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(jsonString);

匿名对象序列化

csharp 复制代码
var anonymousObject = new
{
    Id = 1,
    Description = "测试对象",
    CreateTime = DateTime.Now
};

string jsonString = JsonSerializer.Serialize(anonymousObject);
Console.WriteLine(jsonString);

4. 自定义序列化选项

System.Text.Json 自定义

csharp 复制代码
var options = new JsonSerializerOptions
{
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
    Converters = { new JsonStringEnumConverter() } // 枚举转换为字符串
};

string jsonString = JsonSerializer.Serialize(person, options);

使用特性控制序列化

csharp 复制代码
public class Product
{
    [JsonPropertyName("productName")] // System.Text.Json
    public string Name { get; set; }
    
    [JsonIgnore] // 忽略该属性
    public string InternalCode { get; set; }
    
    [JsonPropertyOrder(1)] // 属性顺序
    public decimal Price { get; set; }
}

5. 性能优化

使用源生成器 (System.Text.Json)

csharp 复制代码
[JsonSerializable(typeof(Person))]
[JsonSerializable(typeof(List<Person>))]
public partial class MyJsonContext : JsonSerializerContext
{
}

// 使用源生成器进行序列化
var person = new Person { Name = "测试", Age = 25 };
string jsonString = JsonSerializer.Serialize(person, MyJsonContext.Default.Person);

选择建议

  • 新项目 :推荐使用 System.Text.Json,性能更好,无需额外依赖
  • 现有项目:如果已经在使用 Newtonsoft.Json,可以继续使用
  • 复杂场景:Newtonsoft.Json 功能更丰富,支持更多复杂场景

两种方法都很常用,根据项目需求和个人偏好选择即可。

相关推荐
维天说3 小时前
CLI-Switch 2026年3月版历史设计:Hook、TTY 隔离与 JSON 状态
java·服务器·json
geovindu11 小时前
CSharp: Flyweight Pattern
开发语言·后端·c#·.net·享元模式·结构型模式
驰骋工作流12 小时前
请假流程:六款.NET工作流引擎实现方式对比
.net·ccflow·工作流引擎二开·.net工作流引擎对比
WarPigs13 小时前
.NET项目app.Config笔记
c#·.net
一颗小行星-1 天前
为什么有的JSON可以带注释?
json
海盗12341 天前
微软技术周报——2026-07-22
microsoft·c#·.net
海盗12341 天前
微软技术日报 ——2026-07-21
microsoft·c#·.net
半亩码田2 天前
【.NET新特性·第8篇】.NET 9 AI 构建基块:Microsoft.Extensions.AI
人工智能·microsoft·.net
Ctrl+Z侠2 天前
.NET WebApi Windows / Linux Docker 全链路压测与瓶颈定位 0 到 1 教程
linux·windows·.net
慧都小妮子2 天前
Aspose.CAD for .NET 26.6 更新发布
pdf·.net·3d渲染·cad·pdf导出·ifc编辑