using System;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;
namespace ColdMint.scripts.serialization;
///
/// JsonSerialization
/// Json序列化工具
///
///
///This serializer is no longer recommended and Yaml is recommended instead of Json.
///此序列化器已不再推荐使用,建议用Yaml代替Json。
///
///
[Obsolete("The Json serializer is out of date, we recommend yaml serialization.\nJson序列化器已过时了,我们推荐使用Yaml。", true)]
public static class JsonSerialization
{
private static readonly JsonSerializerOptions Options = new()
{
//Case-insensitive attribute matching
//不区分大小写的属性匹配
PropertyNameCaseInsensitive = true,
//Try to avoid escape
//尽量避免转义
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
//Enable smart Print
//启用漂亮打印
WriteIndented = true
};
///
/// Read a Json file to type T
/// 读取一个Json文件到T类型
///
///
///
///
public static async Task ReadJsonFileToObj(string path)
{
await using var openStream = File.OpenRead(path);
return await JsonSerializer.DeserializeAsync(openStream, Options);
}
///
/// Serialize the object to Json
/// 将对象序列化为Json
///
///
///
public static string Serialize(object obj)
{
return JsonSerializer.Serialize(obj, Options);
}
///
/// Deserialize Json to an object
/// 将Json反序列化为对象
///
///
///
///
public static T? Deserialize(string json)
{
return JsonSerializer.Deserialize(json, Options);
}
public static async Task ReadJsonFileToObj(Stream openStream)
{
return await JsonSerializer.DeserializeAsync(openStream, Options);
}
}