using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace DebriefingSoftware.Common
{
	public static class DataContractJsonSerializationHelper
	{
		public static string Serialize<T>(T objectToSerialize)
		{
			var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));

			using (var ms = new MemoryStream())
			{
				serializer.WriteObject(ms, objectToSerialize);
				return Encoding.Default.GetString(ms.ToArray());
			}
		}

		public static T Deserialize<T>(string json)
		{
			if (json == null)
			{
				throw new ArgumentNullException("json");
			}

			var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));

			using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
			{
				return (T) serializer.ReadObject(ms);
			}
		}
	}
}