在.NET中操作JSON的常用方法与实践
JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,在.NET开发中被广泛应用,无论是Web API的数据传输、配置文件存储,还是跨平台数据交互,都离不开JSON的处理,本文将详细介绍.NET中操作JSON的常用方法,帮助开发者高效处理JSON数据。
内置JSON序列化与反序列化
.NET Framework 4.5及以上版本和.NET Core提供了内置的JSON处理功能,主要通过System.Text.Json命名空间(.NET Core 3.0+推荐)和Newtonsoft.Json(第三方库,广泛使用)实现。
使用System.Text.Json(.NET Core 3.0+)
System.Text.Json是微软官方推出的高性能JSON库,推荐在新项目中使用。
序列化(对象转JSON字符串):
using System.Text.Json;
var user = new { Name = "张三", Age = 30 };
string jsonString = JsonSerializer.Serialize(user);
// 输出: {"Name":"张三","Age":30}
反序列化(JSON字符串转对象):
string json = "{\"Name\":\"李四\",\"Age\":25}";
var user = JsonSerializer.Deserialize<User>(json);
// User对象: Name="李四", Age=25
使用Newtonsoft.Json(Json.NET)
作为.NET生态中最流行的JSON库,Newtonsoft.Json提供了更丰富的功能和更友好的API。
序列化:
using Newtonsoft.Json;
var product = new { Id = 1, Name = "笔记本电脑", Price = 5999.99 };
string json = JsonConvert.SerializeObject(product);
// 输出: {"Id":1,"Name":"笔记本电脑","Price":5999.99}
反序列化:
string json = "{\"Id\":2,\"Name\":\"智能手机\",\"Price\":3999}";
var product = JsonConvert.DeserializeObject<Product>(json);
// Product对象: Id=2, Name="智能手机", Price=3999
配置文件中的JSON处理
.NET Core广泛使用JSON格式的配置文件(如appsettings.json),通过IConfiguration接口轻松读取。
using Microsoft.Extensions.Configuration;
// 创建配置构建器
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
// 读取配置值
string dbConnectionString = configuration.GetConnectionString("DefaultConnection");
int timeout = configuration.GetValue<int("RequestTimeout");
HTTP请求中的JSON处理
在开发Web API或调用RESTful服务时,JSON是常见的数据格式。
发送HTTP请求(POST/PUT)
using System.Net.Http;
using System.Text;
using System.Text.Json;
var client = new HttpClient();
var data = new { Username = "admin", Password = "123456" };
string json = JsonSerializer.Serialize(data);
var response = await client.PostAsync("https://api.example.com/login",
new StringContent(json, Encoding.UTF8, "application/json"));
接收HTTP响应
string responseJson = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize<ApiResponse>(responseJson);
LINQ to JSON处理动态JSON
对于不确定结构的JSON数据,可以使用LINQ to JSON(Newtonsoft.Json)或JsonElement(System.Text.Json)进行灵活处理。
Newtonsoft.Json的LINQ to JSON
using Newtonsoft.Json.Linq;
string json = @"{
'Name': '王五',
'Age': 28,
'Address': {
'City': '北京',
'Street': '中关村大街'
}
}";
JObject jObject = JObject.Parse(json);
string name = jObject["Name"].ToString();
string city = jObject["Address"]["City"].ToString();
System.Text.Json的JsonElement
using System.Text.Json;
string json = @"{""Name"":""赵六"",""Age"":35}";
JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
string name = root.GetProperty("Name").GetString();
int age = root.GetProperty("Age").GetInt32();
JSON Schema验证
为确保JSON数据符合预期结构,可以使用JSON Schema进行验证。
using Newtonsoft.Json;
using Newtonsoft.Json.Schema;
string schemaJson = @"{
'type': 'object',
'properties': {
'Name': {'type': 'string'},
'Age': {'type': 'integer'}
}
}";
JSchema schema = JSchema.Parse(schemaJson);
JObject json = JObject.Parse("{\"Name\":\"钱七\",\"Age\":40}");
bool isValid = json.IsValid(schema);
性能优化建议
- 选择合适的库:高性能场景优先考虑
System.Text.Json,复杂场景可选Newtonsoft.Json - 复用序列化选项:避免每次序列化都创建新的配置对象
- 使用源生成器:.NET 6+可使用
System.Text.Json的源生成器提升性能 - 避免频繁的JSON转换:在性能敏感场景,可考虑使用二进制格式
常见问题与解决方案
-
日期时间处理:JSON没有日期类型,需自定义序列化格式
// Newtonsoft.Json JsonConvert.SerializeObject(obj, new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss" }); // System.Text.Json options.WriteConverter = new DateTimeConverter("yyyy-MM-dd"); -
循环引用处理:使用
[JsonIgnore]属性或配置循环引用处理// Newtonsoft.Json settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // System.Text.Json options.ReferenceHandler = ReferenceHandler.IgnoreCycles;
.NET提供了多种JSON处理方式,从内置的高性能库到功能丰富的第三方库,开发者可以根据项目需求选择最适合的方案,JSON的序列化、反序列化、动态查询和验证等操作,能够显著提升开发效率和代码质量,随着.NET的不断演进,JSON处理能力也在持续增强,为开发者提供更便捷、更高效的开发体验。



还没有评论,来说两句吧...