2012-08-15 13:20:29 +00:00
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using MediaBrowser.Common.Serialization;
|
|
|
|
|
|
2012-07-21 18:39:47 +00:00
|
|
|
|
namespace MediaBrowser.Common.Net.Handlers
|
2012-07-20 02:22:44 +00:00
|
|
|
|
{
|
2012-08-17 13:16:50 +00:00
|
|
|
|
public abstract class BaseJsonHandler<T> : BaseHandler
|
2012-07-20 02:22:44 +00:00
|
|
|
|
{
|
|
|
|
|
public override string ContentType
|
|
|
|
|
{
|
2012-08-15 13:20:29 +00:00
|
|
|
|
get { return MimeTypes.JsonMimeType; }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private bool _ObjectToSerializeEnsured = false;
|
2012-08-17 13:16:50 +00:00
|
|
|
|
private T _ObjectToSerialize;
|
2012-08-15 13:20:29 +00:00
|
|
|
|
|
|
|
|
|
private void EnsureObjectToSerialize()
|
|
|
|
|
{
|
|
|
|
|
if (!_ObjectToSerializeEnsured)
|
|
|
|
|
{
|
|
|
|
|
_ObjectToSerialize = GetObjectToSerialize();
|
|
|
|
|
|
|
|
|
|
if (_ObjectToSerialize == null)
|
|
|
|
|
{
|
|
|
|
|
StatusCode = 404;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_ObjectToSerializeEnsured = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-17 13:16:50 +00:00
|
|
|
|
private T ObjectToSerialize
|
2012-08-15 13:20:29 +00:00
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
EnsureObjectToSerialize();
|
|
|
|
|
return _ObjectToSerialize;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-17 13:16:50 +00:00
|
|
|
|
protected abstract T GetObjectToSerialize();
|
2012-08-15 13:20:29 +00:00
|
|
|
|
|
|
|
|
|
protected override void PrepareResponse()
|
|
|
|
|
{
|
|
|
|
|
base.PrepareResponse();
|
|
|
|
|
|
|
|
|
|
EnsureObjectToSerialize();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override Task WriteResponseToOutputStream(Stream stream)
|
|
|
|
|
{
|
|
|
|
|
return Task.Run(() =>
|
|
|
|
|
{
|
2012-08-17 13:16:50 +00:00
|
|
|
|
JsonSerializer.SerializeToStream<T>(ObjectToSerialize, stream);
|
2012-08-15 13:20:29 +00:00
|
|
|
|
});
|
2012-07-20 02:22:44 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|