Dave has a great set of NuGet packages to check out. Visit at dotNetTips JsonSerialization class.
My edits are because I wanted less is more and did not want to use the entire library.
Dave has a great set of NuGet packages to check out. Visit at dotNetTips JsonSerialization class.
My edits are because I wanted less is more and did not want to use the entire library.
#nullable enable | |
using System.Diagnostics.CodeAnalysis; | |
using System.Text.Json; | |
namespace Tinkering.Classes; | |
/// <summary> | |
/// Provides methods for serializing and deserializing objects to and from JSON format. | |
/// Base code from David McCarter | |
/// https://github.com/RealDotNetDave/dotNetTips.Spargine/blob/main/source/6/dotNetTips.Spargine.6.Core/Serialization/JsonSerialization.cs | |
/// </summary> | |
public static class JsonSerialization | |
{ | |
public static FileInfo ToFileInfo(string fileName) => new(fileName); | |
public static void SerializeToFile([NotNull] object obj, [NotNull] string file) | |
{ | |
var fileInfo = ToFileInfo(file); | |
if (fileInfo.Directory?.Exists == false) | |
{ | |
fileInfo.Directory?.Create(); | |
} | |
File.WriteAllText(fileInfo.FullName, JsonSerializer.Serialize(obj)); | |
} | |
public static void SerializeToFile([NotNull] object obj, [NotNull] FileInfo file) | |
{ | |
if (file.Directory?.Exists == false) | |
{ | |
file.Directory?.Create(); | |
} | |
File.WriteAllText(file.FullName, JsonSerializer.Serialize(obj)); | |
} | |
public static T DeserializeFromFile<T>([NotNull] string fileName) where T : class | |
{ | |
var jsonString = File.ReadAllText(fileName); | |
return JsonSerializer.Deserialize<T>(jsonString)!; | |
} | |
} |