.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 功能更丰富,支持更多复杂场景

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

相关推荐
C_心欲无痕9 小时前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
玩泥巴的10 小时前
飞书 .NET SDK 事件处理的幂等性与去重机制
c#·.net·二次开发·飞书
喵叔哟11 小时前
20.部署与运维
运维·docker·容器·.net
bugcome_com15 小时前
WPF样式进阶实战:外置样式+MVVM主题切换+样式优先级全解析
c#·.net·wpf
时光追逐者15 小时前
TIOBE 公布 C# 是 2025 年度编程语言
开发语言·c#·.net·.net core·tiobe
REDcker20 小时前
AIGCJson 库解析行为与异常处理指南
c++·json·aigc·c
全栈前端老曹20 小时前
【包管理】read-pkg-up 快速上手教程 - 读取最近的 package.json 文件
前端·javascript·npm·node.js·json·nrm·package.json
半熟的皮皮虾1 天前
又重新写了个PDF工具箱-转换office格式/合并/拆分/删除常见操作都有了
python·程序人生·pdf·flask·开源·json·学习方法
我的golang之路果然有问题1 天前
python中 unicorn 热重启问题和 debug 的 json
java·服务器·前端·python·json
步步为营DotNet1 天前
深度探索.NET 中ValueTask:优化异步性能的轻量级利器
java·spring·.net