using System.IO; using System.Text; using Newtonsoft.Json; namespace SabreTools.Serialization.Readers { /// /// Base class for other JSON serializers /// /// public abstract class JsonFile : BaseBinaryReader { #region IByteReader /// public override T? Deserialize(byte[]? data, int offset) => Deserialize(data, offset, new UTF8Encoding(false)); /// /// Deserialize a byte array into /// /// Type of object to deserialize to /// Byte array to parse /// Offset into the byte array /// Encoding to parse text as /// Filled object on success, null on error public T? Deserialize(byte[]? data, int offset, Encoding encoding) { // If the data is invalid if (data is null || data.Length == 0) return default; // If the offset is out of bounds if (offset < 0 || offset >= data.Length) return default; // Create a memory stream and parse that var dataStream = new MemoryStream(data, offset, data.Length - offset); return Deserialize(dataStream, encoding); } #endregion #region IFileReader /// public override T? Deserialize(string? path) => Deserialize(path, new UTF8Encoding(false)); /// /// Deserialize a file into /// /// Type of object to deserialize to /// Path to deserialize from /// Encoding to parse text as /// Filled object on success, null on error public T? Deserialize(string? path, Encoding encoding) { try { // If we don't have a file if (string.IsNullOrEmpty(path) || !File.Exists(path)) return default; // Open the file for deserialization using var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); return Deserialize(stream, encoding); } catch { // TODO: Handle logging the exception return default; } } #endregion #region IStreamReader /// public override T? Deserialize(Stream? data) => Deserialize(data, new UTF8Encoding(false)); /// /// Deserialize a Stream into /// /// Type of object to deserialize to /// Stream to parse /// Text encoding to use /// Filled object on success, null on error public T? Deserialize(Stream? data, Encoding encoding) { // If the stream is invalid if (data is null || !data.CanRead) return default; try { // Setup the serializer and the reader var serializer = JsonSerializer.Create(); var streamReader = new StreamReader(data, encoding); var jsonReader = new JsonTextReader(streamReader); // Perform the deserialization and return return serializer.Deserialize(jsonReader); } catch { // Ignore the actual error return default; } } #endregion } }