Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5Mobile wallpaper 6Mobile wallpaper 7Mobile wallpaper 8
174 字
1 分钟
使用C#读取,写入JSON文件
// 定义数据
public class Item
{
// Json 注解
[JsonPropertyName("user_name")]
public string Name { get; set; }
[JsonPropertyName("age")]
public int Age { get; set; }
[JsonPropertyName("using_skills")] // JSON 里为 using_skills
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] // 条件忽略, 为Null忽略
public List<string>? Skills { get; set; }
}
public static void Main(string[] args)
{
string path = @"C:\Projects\C#\ConsoleTest\ConsoleTest";
var item = new Item
{
Name = "ZhangSan",
Age = 24,
Skills = new List<string> { "CSharp", "XAML" }
};
var items = new List<Item>
{
item,
new Item
{
Name = "ZhangSan",
Age = 24,
Skills = null,
}
};
var options = new JsonSerializerOptions
{
WriteIndented = true // 配置缩进
};
// 转为json字符串
string json = JsonSerializer.Serialize(items, options);
// 写入
File.WriteAllText(Path.Combine(path, "demo.json"), json);
// 读取json文件,反序列化
json = File.ReadAllText(Path.Combine(path, "demo.json"));
List<Item>? newItem = JsonSerializer.Deserialize<List<Item>>(json);
if (newItem == null) { return; }
foreach (var itm in newItem)
{
Console.WriteLine(itm.Name);
Console.WriteLine(itm.Age);
Console.WriteLine(itm.Skills);
}
}
使用C#读取,写入JSON文件
https://mikuas.top/posts/c_sharp/r_w_json_file/
作者
Mikuas
发布于
2025-10-15
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时