Nuget安装Newtonsoft后,引入命名空间:
    using Newtonsoft.Json;

    1. /// <summary>
    2. /// 读取Josn文件为Model对象
    3. /// </summary>
    4. /// <typeparam name="T">Model对象类型</typeparam>
    5. /// <param name="jspath">Josn文件路径(含【文件名】与【扩展名】)</param>
    6. /// <param name="dm">Model对象</param>
    7. /// <returns>true:读取成功;false:读取失败</returns>
    8. public static bool ReadJson<T>(string jspath, out T dm)
    9. {
    10. if (File.Exists(jspath))
    11. {
    12. string jstr = File.ReadAllText(jspath);
    13. dm = JsonConvert.DeserializeObject<T>(jstr);
    14. return true;
    15. }
    16. else
    17. {
    18. dm = default;
    19. return false;
    20. }
    21. }
    22. /// <summary>
    23. /// 将Model对象写出为Josn文件
    24. /// </summary>
    25. /// <typeparam name="T">Model对象类型</typeparam>
    26. /// <param name="dm">Model对象</param>
    27. /// <param name="jspath">Josn文件路径(含【文件名】与【扩展名】)</param>
    28. /// <returns>true:写出成功;false:写出失败</returns>
    29. public static bool WriteJson<T>(T dm, string jspath)
    30. {
    31. if (Directory.Exists(Path.GetDirectoryName(jspath)))
    32. {
    33. string jstr = JsonConvert.SerializeObject(dm);
    34. File.WriteAllText(jspath, jstr);
    35. return true;
    36. }
    37. else return false;
    38. }