JSON 是前后端数据交互的常用格式,Newtonsoft.Json(Json.NET)是 C# 中最流行的 JSON 处理库。
案例:JSON 工具类(需安装 Newtonsoft.Json 包)
using Newtonsoft.Json; // 定义实体类 public class User { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } } public class JsonHelper { // 对象序列化为JSON字符串 public static string Serialize(object obj) { // 格式化输出(便于阅读) return JsonConvert.SerializeObject(obj, Formatting.Indented); } // JSON字符串反序列化为对象 public static T Deserialize<T>(string json) { if (string.IsNullOrEmpty(json)) return default(T); return JsonConvert.DeserializeObject<T>(json); } } // 调用示例 // 序列化 User user = new User { Id = 1, Name = "张三", Age = 25, Email = "zhangsan@example.com" }; string json = JsonHelper.Serialize(user); Console.WriteLine("序列化结果:"); Console.WriteLine(json); // 反序列化 string jsonStr = @"{ ""Id"": 2, ""Name"": ""李四"", ""Age"": 30, ""Email"": ""lisi@example.com"" }"; User deserializedUser = JsonHelper.Deserialize<User>(jsonStr); Console.WriteLine("\n反序列化结果:"); Console.WriteLine($"ID:{deserializedUser.Id},姓名:{deserializedUser.Name}"); 安装方式:NuGet 搜索 Newtonsoft.Json 并安装。