Newtonsoft.Json (也称为 Json.NET) 是一种适用于 .NET 的常用高性能 JSON 框架,用于处理 JSON 数据。它提供了高性能的 JSON 序列化和反序列化功能。
安装
通过 NuGet 安装
基本用法
1. 序列化对象为 JSON 字符串
using Newtonsoft.Json;
var product = new Product
{
Name = "Apple",
Expiry = new DateTime(2008, 12, 28),
Sizes = new[] { "Small", "Medium", "Large" }
};
string json = JsonConvert.SerializeObject(product);
// 输出:
// {"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small","Medium","Large"]}
//处理object类型的数据json序列化
object[,] config = worksheet.Cells[1, 1, maxHang, maxLie].Value as object[,];
string customJson = JsonConvert.SerializeObject(config);
var bytes = Encoding.UTF8.GetBytes(customJson);
var path = @"D:\jsonFile.bytes";
File.WriteAllBytes(path, bytes);
2. 反序列化 JSON 字符串为对象
string json = @"{
'Name': 'Apple',
'Expiry': '2008-12-28T00:00:00',
'Sizes': ['Small', 'Medium', 'Large']
}";
Product product = JsonConvert.DeserializeObject<Product>(json);
Console.WriteLine(product.Name); // 输出: Apple
3. 格式化 JSON 输出
对字符串进行缩进换行,更易于阅读
string json = JsonConvert.SerializeObject(product, Formatting.Indented);
// 输出格式化的 JSON:
// {
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
// }
4、大型 JSON 处理的流式处理
对于大型 JSON 处理,可以使用 JsonTextReader
和 JsonTextWriter
进行流式处理:
// 读取
using (StreamReader file = File.OpenText("largefile.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o = (JObject)JToken.ReadFrom(reader);
// 处理数据
}
// 写入
using (StreamWriter file = File.CreateText("largefile.json"))
using (JsonTextWriter writer = new JsonTextWriter(file))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, largeObject);
}