C# (.NET) 中的 JSON 处理:完全指南
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,已成为 Web API 和配置文件的标配。在 C# (.NET) 生态系统中,有两个主要的 JSON 处理工具:久经考验的 Newtonsoft.Json 库(也称为 Json.NET)和自 .NET Core 3.0 起引入的现代内置库 System.Text.Json。本文将详细解析这两个库的功能及使用示例。
1. Newtonsoft.Json (Json.NET)
多年来,Newtonsoft.Json 一直是 C# 中处理 JSON 的事实标准。它提供了丰富的功能,包括灵活的序列化、对 LINQ to JSON 的支持以及动态类型处理。
安装
通过 NuGet 包管理器安装,请执行以下命令:
Install-Package Newtonsoft.Json或通过 .NET CLI:
dotnet add package Newtonsoft.Json基本操作:序列化与反序列化
序列化是将 C# 对象转换为 JSON 字符串的过程。反序列化则是相反的过程。
using Newtonsoft.Json;
public class Person{ public string Name { get; set; } public int Age { get; set; } public List<string> Hobbies { get; set; }}
// 序列化Person person = new Person{ Name = "阿列克谢", Age = 30, Hobbies = new List<string> { "编程", "阅读", "旅行" }};
string json = JsonConvert.SerializeObject(person, Formatting.Indented);Console.WriteLine(json);
// 反序列化string jsonInput = @"{'Name':'玛丽亚','Age':25,'Hobbies':['绘画','瑜伽']}";Person deserializedPerson = JsonConvert.DeserializeObject<Person>(jsonInput);Console.WriteLine($"姓名: {deserializedPerson.Name}, 年龄: {deserializedPerson.Age}");处理动态数据
Newtonsoft.Json 支持动态类型,这在处理未知结构的 JSON 时非常方便。
dynamic dynamicObject = JsonConvert.DeserializeObject("{'Name':'伊万','Score':95.5}");Console.WriteLine($"学生: {dynamicObject.Name}, 分数: {dynamicObject.Score}");LINQ to JSON
该库提供了强大的 API,可使用 LINQ 查询 JSON 数据。
using Newtonsoft.Json.Linq;
string json = @"{ 'users': [ {'name': '安娜', 'age': 28}, {'name': '彼得', 'age': 35}, {'name': '叶莲娜', 'age': 22} ]}";
JObject obj = JObject.Parse(json);var youngUsers = obj["users"] .Where(u => (int)u["age"] < 30) .Select(u => (string)u["name"]);
foreach (var name in youngUsers){ Console.WriteLine(name); // 输出:安娜, 叶莲娜}2. System.Text.Json
System.Text.Json 是微软推出的现代库,针对高性能和低内存消耗进行了优化。它内置于 .NET 中,无需安装额外的包。
基本操作
using System.Text.Json;using System.Text.Json.Serialization;
public class Product{ [JsonPropertyName("product_name")] public string Name { get; set; } public decimal Price { get; set; } [JsonIgnore] public string InternalCode { get; set; }}
// 序列化Product product = new Product{ Name = "笔记本电脑", Price = 75000.50m, InternalCode = "INT-001"};
string json = JsonSerializer.Serialize(product, new JsonSerializerOptions { WriteIndented = true });Console.WriteLine(json);
// 反序列化string jsonInput = @"{""product_name"":""智能手机"",""Price"":45000.00}";Product deserializedProduct = JsonSerializer.Deserialize<Product>(jsonInput);Console.WriteLine($"商品: {deserializedProduct.Name}, 价格: {deserializedProduct.Price}");