using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tango.Serialization
{
///
/// Represents a data serializer for serializing data using the light weight textual Json format.
///
public class JsonDataSerializer : IDataSerializer
{
///
/// Serialize object to a file.
///
/// Type of specified object.
/// The specified object.
/// The full path to the file to write.
public void SerializeToFile(T obj, string filePath)
{
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
SerializeToStream(obj, fs);
}
}
///
/// Deserialize object from a file.
///
/// Type of object to deserialize.
/// The full path of the data file.
/// The resulting object.
public T DeserializeFromFile(string filePath)
{
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
return DeserializeFromStream(fs);
}
}
///
/// Serialize object to stream.
///
/// Type of specified object.
/// The specified object.
/// The stream to write.
public void SerializeToStream(T obj, Stream st)
{
JsonSerializer serializer = new JsonSerializer();
using (StreamWriter streamReader = new StreamWriter(st))
{
serializer.Serialize(streamReader, obj);
}
}
///
/// Deserialize object from stream.
///
/// Type of object to deserialize.
/// Stream to read from.
/// The resulting object.
public T DeserializeFromStream(Stream st)
{
JsonSerializer serializer = new JsonSerializer();
T data;
using (StreamReader streamReader = new StreamReader(st))
{
data = (T)serializer.Deserialize(streamReader, typeof(T));
}
return data;
}
///
/// Returns the serializer full name.
///
///
public override string ToString()
{
return SerializationHelper.GetSerializerName(this);
}
}
}