NuGet:搜索System.Text.Json 安装
引用:
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;
using System.IO;
序列化方法:
private static JsonSerializerOptions serializerOptions = new JsonSerializerOptions() { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; public static string JsonSerialize<T>(T obj) => JsonSerializer.Serialize(obj, serializerOptions); public static void JsonSerialize<T>(T obj, string fileName) { using (FileStream createStream = File.Create(fileName)) { JsonSerializer.Serialize(createStream, obj, serializerOptions); } } public static async Task JsonSerializeAsync<T>(T obj, string fileName) { using (FileStream createStream = File.Create(fileName)) { await JsonSerializer.SerializeAsync(createStream, obj, serializerOptions); } }
反序列化方法:
public static void JsonDeserialize<T>(string jsonString, out T obj) => obj = JsonSerializer.Deserialize<T>(jsonString); public static T JsonDeserialize<T>(string fileName) => JsonSerializer.Deserialize<T>(File.ReadAllText(fileName)); public static async Task JsonDeserializeAsync<T>(string fileName) { using (FileStream openStream = File.OpenRead(fileName)) { await JsonSerializer.DeserializeAsync<T>(openStream); } }