using System;
using System.IO;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
// 读取 JSON 文件路径
string filePath = "example.json";
// 检查文件是否存在
if (File.Exists(filePath))
{
// 读取 JSON 文件内容
string jsonContent = File.ReadAllText(filePath);
// 将 JSON 字符串反序列化为对象
MyData data = JsonConvert.DeserializeObject<MyData>(jsonContent);
// 输出读取到的数据
Console.WriteLine($"Name: {data.Name}, Age: {data.Age}");
}
else
{
Console.WriteLine("文件不存在");
}
}
}
// 定义一个类来匹配 JSON 文件中的结构
public class MyData
{
public string Name { get; set; }
public int Age { get; set; }
}
System 和 System.IO 命名空间来处理文件操作,使用 Newtonsoft.Json 命名空间来进行 JSON 处理。filePath 来存储 JSON 文件的路径。File.Exists 方法检查文件是否存在。File.ReadAllText 方法读取整个文件的内容,并将其存储在字符串 jsonContent 中。JsonConvert.DeserializeObject<T> 方法将 JSON 字符串反序列化为 MyData 类型的对象。MyData 类,其属性与 JSON 文件中的结构相匹配。上一篇:c#矩阵运算
下一篇:c# selectmany
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站