using System.IO; using System.Text; using Newtonsoft.Json; using SabreTools.Serialization.Interfaces; namespace SabreTools.Serialization.Streams { /// /// Base class for other JSON serializers /// /// public partial class JsonFile : IStreamSerializer { /// public Stream? Serialize(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 == 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.Seek(0, SeekOrigin.Begin); return stream; } } }