推荐使用System.Text.Json读取JSON文件和解析字符串:读取文件用File.ReadAllText+JsonSerializer.Deserialize;解析字符串同理,或用JsonDocument提取字段;Newtonsoft.Json兼容性好但性能较低。
在C#中读取JSON文件和解析JSON字符串,最常用、推荐的方式是使用 System.Text.Json(.NET Core 3.0+ 和 .NET 5+ 内置)或 Newtonsoft.Json(即 Json.NET,兼容性更广)。下面分两种常见场景说明,重点讲清怎么做、注意什么。
假设你有一个 config.json 文件,内容如下:
{
"name": "张三",
"age": 28,
"isActive": true
}对应定义一个 C# 类:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsActive { get; set; }
}用 System.Text.Json 读取并解析:
using System.Text.Json;string json = File.ReadAllText("config.json"); Person person = JsonSerializer.Deserialize
(json);
✅ 小提示:
Name ↔ "name"),无需额外配置[JsonPropertyName("xxx")] 特性标注FileNotFoundException,建议加 try-catch 或先判断 File.Exists()
比如从 A
PI 接口拿到一段 JSON 字符串:
string jsonString = @"{""id"":123,""title"":""Hello World""}";同样用 JsonSerializer.Deserialize 即可:
var obj = JsonSerializer.Deserialize(jsonString);
如果只是临时提取个别字段,不想定义完整类,可以用 JsonDocument 或 JsonElement:
using JsonDocument doc = JsonDocument.Parse(jsonString);
string title = doc.RootElement.GetProperty("title").GetString(); // 返回 "Hello World"✅ 这种方式适合结构不固定、只取少量字段的场景,性能好、内存占用低。
安装 NuGet 包:Install-Package Newtonsoft.Json
读取文件:
string json = File.ReadAllText("data.json");
Person p = JsonConvert.DeserializeObject(json); 解析字符串:
JObject jObj = JObject.Parse(jsonString); string title = jObj["title"]?.ToString();
✅ 它支持更多格式(如注释、单引号)、语法更灵活,但 System.Text.Json 性能更好、更轻量,新项目优先选它。
List 或子类即可,自动映射[JsonIgnore];Newtonsoft 用 [JsonIgnore] 或 [JsonProperty(Required = Required.Default)]
基本上就这些。选 System.Text.Json 是当前主流,简单、快、无第三方依赖;有特殊需求(比如需要动态处理或兼容旧代码)再上 Newtonsoft.Json。