Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created October 24, 2024 15:00
Show Gist options
  • Save karenpayneoregon/c0980a9f33a6e48b7ffa94f4b99e10f9 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/c0980a9f33a6e48b7ffa94f4b99e10f9 to your computer and use it in GitHub Desktop.
David McCarter JsonSerialization class

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)!;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment