2013-05-13 02:52:55 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.IO;
|
2013-09-19 00:30:37 +00:00
|
|
|
|
using System.Linq.Expressions;
|
2013-05-13 02:52:55 +00:00
|
|
|
|
using Newtonsoft.Json;
|
|
|
|
|
using Newtonsoft.Json.Converters;
|
|
|
|
|
using Newtonsoft.Json.Serialization;
|
|
|
|
|
|
|
|
|
|
namespace NzbDrone.Common.Serializer
|
|
|
|
|
{
|
|
|
|
|
public static class Json
|
|
|
|
|
{
|
2013-09-19 00:24:50 +00:00
|
|
|
|
private static readonly JsonSerializer Serializer;
|
|
|
|
|
private static readonly JsonSerializerSettings SerializerSetting;
|
2013-05-13 02:52:55 +00:00
|
|
|
|
|
|
|
|
|
static Json()
|
|
|
|
|
{
|
2013-09-19 00:24:50 +00:00
|
|
|
|
SerializerSetting = new JsonSerializerSettings
|
|
|
|
|
{
|
|
|
|
|
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
|
|
|
|
|
NullValueHandling = NullValueHandling.Ignore,
|
|
|
|
|
Formatting = Formatting.Indented,
|
|
|
|
|
DefaultValueHandling = DefaultValueHandling.Include,
|
|
|
|
|
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
SerializerSetting.Converters.Add(new StringEnumConverter { CamelCaseText = true });
|
|
|
|
|
SerializerSetting.Converters.Add(new IntConverter());
|
2013-09-19 00:30:37 +00:00
|
|
|
|
SerializerSetting.Converters.Add(new VersionConverter());
|
2013-09-19 00:24:50 +00:00
|
|
|
|
|
|
|
|
|
Serializer = JsonSerializer.Create(SerializerSetting);
|
|
|
|
|
|
2013-05-13 02:52:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
2013-09-19 00:24:50 +00:00
|
|
|
|
public static T Deserialize<T>(string json) where T : new()
|
2013-05-13 02:52:55 +00:00
|
|
|
|
{
|
2013-09-19 00:24:50 +00:00
|
|
|
|
return JsonConvert.DeserializeObject<T>(json, SerializerSetting);
|
2013-05-13 02:52:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static object Deserialize(string json, Type type)
|
|
|
|
|
{
|
2013-09-19 00:24:50 +00:00
|
|
|
|
return JsonConvert.DeserializeObject(json, type, SerializerSetting);
|
2013-05-13 02:52:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
2013-05-29 21:29:51 +00:00
|
|
|
|
public static string ToJson(this object obj)
|
2013-05-13 02:52:55 +00:00
|
|
|
|
{
|
2013-09-19 00:24:50 +00:00
|
|
|
|
return JsonConvert.SerializeObject(obj, SerializerSetting);
|
2013-05-13 02:52:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void Serialize<TModel>(TModel model, TextWriter outputStream)
|
|
|
|
|
{
|
|
|
|
|
var jsonTextWriter = new JsonTextWriter(outputStream);
|
2013-09-19 00:24:50 +00:00
|
|
|
|
Serializer.Serialize(jsonTextWriter, model);
|
2013-05-13 02:52:55 +00:00
|
|
|
|
jsonTextWriter.Flush();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void Serialize<TModel>(TModel model, Stream outputStream)
|
|
|
|
|
{
|
|
|
|
|
Serialize(model, new StreamWriter(outputStream));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|