using System.IO; using System.Text; using Newtonsoft.Json; using SabreTools.IO.Extensions; namespace SabreTools.Serialization.Writers { /// /// Base class for other JSON serializers /// /// public class JsonFile : BaseBinaryWriter { #region IByteWriter /// public override byte[]? SerializeArray(T? obj) => SerializeArray(obj, new UTF8Encoding(false)); /// /// Serialize a into a byte array /// /// Type of object to serialize from /// Data to serialize /// Encoding to parse text as /// Filled object on success, null on error public byte[]? SerializeArray(T? obj, Encoding encoding) { using var stream = Serialize(obj, encoding); if (stream is null) return null; byte[] bytes = new byte[stream.Length]; int read = stream.Read(bytes, 0, bytes.Length); return bytes; } #endregion #region IFileWriter /// public override bool SerializeFile(T? obj, string? path) => Serialize(obj, path, new UTF8Encoding(false)); /// /// Serialize a into a file /// /// Type of object to serialize from /// Data to serialize /// Path to the file to serialize to /// Encoding to parse text as /// True on successful serialization, false otherwise public bool Serialize(T? obj, string? path, Encoding encoding) { if (string.IsNullOrEmpty(path)) return false; using var stream = Serialize(obj, encoding); if (stream is null) return false; using var fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None); stream.BlockCopy(fs); fs.Flush(); return true; } #endregion #region IStreamWriter /// public override Stream? SerializeStream(T? obj) => Serialize(obj, new UTF8Encoding(false)); /// /// Serialize a into a Stream /// /// Type of object to serialize from /// Data to serialize /// /// Filled object on success, null on error public Stream? Serialize(T? obj, Encoding encoding) { // If the object is null if (obj is null) return null; // Setup the serializer and the writer var serializer = JsonSerializer.Create(); var stream = new MemoryStream(); var streamWriter = new StreamWriter(stream, encoding); var jsonWriter = new JsonTextWriter(streamWriter); // Perform the deserialization and return serializer.Serialize(jsonWriter, obj); stream.SeekIfPossible(0, SeekOrigin.Begin); return stream; } #endregion } }