using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


public static class JsonHelper
{
    public static T DeserializeFromFile<T>(string filePath)
    {
        if (File.Exists(filePath))
        {
            string json = File.ReadAllText(filePath);
            try
            {
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception)
            {

                return default;
            }
        }
        return default;
    }
    public static T DeserializeFromString<T>(string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }
    public static void WriteToFile(string path, string content)
    {
        try
        {
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
            using (var writer = new StreamWriter(fs))
            {
                writer.Write(content);
                writer.Flush();
                fs.Flush(true); // 强制刷新到底层存储介质
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("写入失败：" + ex.Message);
        }
    }

    public static void SerializeObject(string filePath, object obj)
    {
        // 序列化对象为字符串
        string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
        // 写入文件
        string directoryPath = Path.GetDirectoryName(filePath);
        if (directoryPath == "")
            //File.WriteAllText(filePath, json);
            WriteToFile(filePath, json);
        else if (!Directory.Exists(directoryPath))
        {
            Directory.CreateDirectory(directoryPath);
            //File.WriteAllText(filePath, json);
            WriteToFile(filePath, json);
        }
        else
            //File.WriteAllText(filePath, json);
            WriteToFile(filePath, json);
    }
    public static string SerializeObject(object obj)
    {
        // 序列化对象为字符串
        string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
        return json;
    }
    public static T CloneObject<T>(T obj)
    {
        return JsonConvert.DeserializeObject<T>(SerializeObject(obj));
    }
}

