1
0
mirror of https://github.com/Sonarr/Sonarr.git synced 2024-12-16 11:37:58 +02:00

added custom IntConverter to get around the mono bug

http://json.codeplex.com/workitem/24176
This commit is contained in:
Keivan Beigi 2013-09-18 17:24:50 -07:00
parent 904061c2f0
commit 41c5619d1b
15 changed files with 122 additions and 56 deletions
NzbDrone.Common
NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetProviderTests
NzbDrone.Core
NzbDrone.Libraries.Test
NzbDrone.Test.Common

View File

@ -98,6 +98,7 @@
<Compile Include="Messaging\IEvent.cs" />
<Compile Include="Messaging\IMessage.cs" />
<Compile Include="PathEqualityComparer.cs" />
<Compile Include="Serializer\IntConverter.cs" />
<Compile Include="Services.cs" />
<Compile Include="TPL\LimitedConcurrencyLevelTaskScheduler.cs" />
<Compile Include="Security\IgnoreCertErrorPolicy.cs" />

View File

@ -2,9 +2,9 @@
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using NzbDrone.Common.Contract;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Serializer;
namespace NzbDrone.Common
{
@ -27,7 +27,7 @@ private static void PostData(string url, object message)
{
try
{
var json = JsonConvert.SerializeObject(message);
var json = message.ToJson();
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = TIMEOUT;

View File

@ -0,0 +1,39 @@
using System;
using Newtonsoft.Json;
namespace NzbDrone.Common.Serializer
{
public class IntConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
}
else
{
writer.WriteValue(value);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (!CanConvert(objectType))
{
throw new JsonSerializationException("Can't convert type " + existingValue.GetType().FullName + " to number");
}
if (objectType == typeof(Int64))
{
return Convert.ToInt64(reader.Value);
}
return Convert.ToInt32(reader.Value);
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Int32) || objectType == typeof(Int64) || objectType == typeof(int);
}
}
}

View File

@ -8,42 +8,47 @@ namespace NzbDrone.Common.Serializer
{
public static class Json
{
private static readonly JsonSerializer JsonNetSerializer;
private static readonly JsonSerializer Serializer;
private static readonly JsonSerializerSettings SerializerSetting;
static Json()
{
JsonNetSerializer = new JsonSerializer()
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented,
DefaultValueHandling = DefaultValueHandling.Include,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
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());
Serializer = JsonSerializer.Create(SerializerSetting);
JsonNetSerializer.Converters.Add(new StringEnumConverter { CamelCaseText = true });
}
public static T Deserialize<T>(string json) where T : class, new()
public static T Deserialize<T>(string json) where T : new()
{
return JsonConvert.DeserializeObject<T>(json);
return JsonConvert.DeserializeObject<T>(json, SerializerSetting);
}
public static object Deserialize(string json, Type type)
{
return JsonConvert.DeserializeObject(json, type);
return JsonConvert.DeserializeObject(json, type, SerializerSetting);
}
public static string ToJson(this object obj)
{
return JsonConvert.SerializeObject(obj);
return JsonConvert.SerializeObject(obj, SerializerSetting);
}
public static void Serialize<TModel>(TModel model, TextWriter outputStream)
{
var jsonTextWriter = new JsonTextWriter(outputStream);
JsonNetSerializer.Serialize(jsonTextWriter, model);
Serializer.Serialize(jsonTextWriter, model);
jsonTextWriter.Flush();
}

View File

@ -4,6 +4,7 @@
using Moq;
using NUnit.Framework;
using NzbDrone.Common;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Download.Clients.Nzbget;
using NzbDrone.Core.Parser.Model;
@ -51,9 +52,16 @@ private void WithFailResponse()
[Test]
public void should_add_item_to_queue()
{
var command = new JsonRequest
{
Method = "appendurl",
Params = new object[] { "30.Rock.S01E01.Pilot.720p.hdtv.nzb", "TV", 50, false, "http://www.nzbdrone.com" }
};
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.PostCommand("192.168.5.55:6789", "nzbget", "pass",
It.Is<String>(c => c.Equals("{\"method\":\"appendurl\",\"params\":[\"30.Rock.S01E01.Pilot.720p.hdtv.nzb\",\"TV\",50,false,\"http://www.nzbdrone.com\"]}"))))
It.Is<String>(c => c.Equals(command.ToJson()))))
.Returns("{\"version\": \"1.1\",\"result\": true}");
Mocker.Resolve<NzbgetClient>().DownloadNzb(_remoteEpisode);

View File

@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using NLog;
using NzbDrone.Common;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Parser.Model;
@ -36,11 +36,11 @@ public void DownloadNzb(RemoteEpisode remoteEpisode)
};
_logger.Info("Adding report [{0}] to the queue.", title);
var response = PostCommand(JsonConvert.SerializeObject(command));
var response = PostCommand(command.ToJson());
CheckForError(response);
var success = JsonConvert.DeserializeObject<EnqueueResponse>(response).Result;
var success = Json.Deserialize<EnqueueResponse>(response).Result;
_logger.Debug("Queue Response: [{0}]", success);
}
@ -61,11 +61,11 @@ public virtual IEnumerable<QueueItem> GetQueue()
Params = null
};
var response = PostCommand(JsonConvert.SerializeObject(command));
var response = PostCommand(command.ToJson());
CheckForError(response);
var itmes = JsonConvert.DeserializeObject<NzbGetQueue>(response).QueueItems;
var itmes = Json.Deserialize<NzbGetQueue>(response).QueueItems;
foreach (var nzbGetQueueItem in itmes)
{
@ -101,11 +101,11 @@ public virtual VersionModel GetVersion(string host = null, int port = 0, string
};
var address = String.Format(@"{0}:{1}", host, port);
var response = _httpProvider.PostCommand(address, username, password, JsonConvert.SerializeObject(command));
var response = _httpProvider.PostCommand(address, username, password, command.ToJson());
CheckForError(response);
return JsonConvert.DeserializeObject<VersionModel>(response);
return Json.Deserialize<VersionModel>(response);
}
public virtual string Test(string host, int port, string username, string password)
@ -134,7 +134,7 @@ private string PostCommand(string command)
private void CheckForError(string response)
{
var result = JsonConvert.DeserializeObject<JsonError>(response);
var result = Json.Deserialize<JsonError>(response);
if (result.Error != null)
throw new ApplicationException(result.Error.ToString());

View File

@ -1,11 +1,11 @@
using System;
using System.Collections.Generic;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using NzbDrone.Common;
using NzbDrone.Common.Cache;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Parser.Model;
using RestSharp;
@ -107,7 +107,7 @@ public IEnumerable<QueueItem> GetQueue()
CheckForError(response);
var sabQueue = JsonConvert.DeserializeObject<SabQueue>(JObject.Parse(response).SelectToken("queue").ToString()).Items;
var sabQueue = Json.Deserialize<SabQueue>(JObject.Parse(response).SelectToken("queue").ToString()).Items;
var queueItems = new List<QueueItem>();
@ -134,7 +134,7 @@ public virtual List<SabHistoryItem> GetHistory(int start = 0, int limit = 0)
CheckForError(response);
var items = JsonConvert.DeserializeObject<SabHistory>(JObject.Parse(response).SelectToken("history").ToString()).Items;
var items = Json.Deserialize<SabHistory>(JObject.Parse(response).SelectToken("history").ToString()).Items;
return items ?? new List<SabHistoryItem>();
}
@ -166,7 +166,7 @@ public virtual SabCategoryModel GetCategories(string host = null, int port = 0,
if (String.IsNullOrWhiteSpace(response))
return new SabCategoryModel { categories = new List<string>() };
var categories = JsonConvert.DeserializeObject<SabCategoryModel>(response);
var categories = Json.Deserialize<SabCategoryModel>(response);
return categories;
}
@ -199,7 +199,7 @@ public virtual SabVersionModel GetVersion(string host = null, int port = 0, stri
if (String.IsNullOrWhiteSpace(response))
return null;
var version = JsonConvert.DeserializeObject<SabVersionModel>(response);
var version = Json.Deserialize<SabVersionModel>(response);
return version;
}
@ -232,7 +232,7 @@ private string GetSabRequest(string action)
private void CheckForError(string response)
{
var result = JsonConvert.DeserializeObject<SabJsonError>(response);
var result = Json.Deserialize<SabJsonError>(response);
if (result.Status != null && result.Status.Equals("false", StringComparison.InvariantCultureIgnoreCase))
throw new ApplicationException(result.Error);

View File

@ -1,4 +1,4 @@
using Newtonsoft.Json;
using NzbDrone.Common.Serializer;
namespace NzbDrone.Core.Indexers
{
@ -25,7 +25,7 @@ public IndexerSettingProvider(IIndexerRepository indexerRepository)
return new TSetting();
}
return JsonConvert.DeserializeObject<TSetting>(indexerDef.Settings);
return Json.Deserialize<TSetting>(indexerDef.Settings);
}
}
}

View File

@ -1,4 +1,4 @@
using Newtonsoft.Json;
using NzbDrone.Common.Serializer;
namespace NzbDrone.Core.Notifications
{
@ -25,7 +25,7 @@ public NotificationSettingsProvider(INotificationRepository notificationReposito
return new TSetting();
}
return JsonConvert.DeserializeObject<TSetting>(indexerDef.Settings);
return Json.Deserialize<TSetting>(indexerDef.Settings);
}
}
}

View File

@ -2,9 +2,9 @@
using System.Collections.Generic;
using System.Linq;
using NLog;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NzbDrone.Common;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Model.Xbmc;
using NzbDrone.Core.Tv;
@ -72,7 +72,7 @@ public List<ActivePlayer> GetActivePlayers(XbmcSettings settings)
if (CheckForError(response))
return new List<ActivePlayer>();
var result = JsonConvert.DeserializeObject<ActivePlayersEdenResult>(response);
var result = Json.Deserialize<ActivePlayersEdenResult>(response);
return result.Result;
}
@ -97,7 +97,7 @@ public bool CheckForError(string response)
if (response.StartsWith("{\"error\""))
{
var error = JsonConvert.DeserializeObject<ErrorResult>(response);
var error = Json.Deserialize<ErrorResult>(response);
var code = error.Error["code"];
var message = error.Error["message"];
@ -159,7 +159,7 @@ private void UpdateLibrary(XbmcSettings settings, Series series)
if (CheckForError(response)) return;
_logger.Trace(" from response");
var result = JsonConvert.DeserializeObject<XbmcJsonResult<String>>(response);
var result = Json.Deserialize<XbmcJsonResult<String>>(response);
if (!result.Result.Equals("OK", StringComparison.InvariantCultureIgnoreCase))
{
@ -185,7 +185,7 @@ private List<TvShow> GetSeries(XbmcSettings settings)
if (CheckForError(response))
return new List<TvShow>();
var result = JsonConvert.DeserializeObject<TvShowResponse>(response);
var result = Json.Deserialize<TvShowResponse>(response);
var shows = result.Result.TvShows;
return shows;

View File

@ -1,12 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using NzbDrone.Common;
using NzbDrone.Common.Instrumentation;
using NzbDrone.Core.Messaging;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Messaging.Commands;
using NzbDrone.Core.Tv;
using NzbDrone.Core.Model.Xbmc;
@ -63,7 +62,7 @@ public XbmcVersion GetJsonVersion(XbmcSettings settings)
var response = _httpProvider.PostCommand(settings.Address, settings.Username, settings.Password, postJson.ToString());
Logger.Trace("Getting version from response");
var result = JsonConvert.DeserializeObject<XbmcJsonResult<JObject>>(response);
var result = Json.Deserialize<XbmcJsonResult<JObject>>(response);
var versionObject = result.Result.Property("version");
@ -71,7 +70,7 @@ public XbmcVersion GetJsonVersion(XbmcSettings settings)
return new XbmcVersion((int)versionObject.Value);
if (versionObject.Value.Type == JTokenType.Object)
return JsonConvert.DeserializeObject<XbmcVersion>(versionObject.Value.ToString());
return Json.Deserialize<XbmcVersion>(versionObject.Value.ToString());
throw new InvalidCastException("Unknown Version structure!: " + versionObject);
}

View File

@ -1,3 +1,5 @@
using System;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Serializer;
using NzbDrone.Test.Common;
@ -9,15 +11,19 @@ public class JsonFixture : TestBase
{
public class TypeWithNumbers
{
public int Id { get; set; }
public int Int32 { get; set; }
public Int64 Int64 { get; set; }
public int? nullableIntIsNull { get; set; }
public int? nullableWithValue { get; set; }
}
[Test]
public void should_be_able_to_deserialize_numbers()
{
var quality = new TypeWithNumbers { Id = 12 };
var quality = new TypeWithNumbers { Int32 = Int32.MaxValue, Int64 = Int64.MaxValue, nullableWithValue = 12 };
var result = Json.Deserialize<TypeWithNumbers>(quality.ToJson());
Json.Deserialize<TypeWithNumbers>(quality.ToJson());
result.ShouldHave().AllProperties().EqualTo(quality);
}
}
}

View File

@ -33,6 +33,14 @@
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="FluentAssertions, Version=2.1.0.0, Culture=neutral, PublicKeyToken=33f2691a05b67b6a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\FluentAssertions.2.1.0.0\lib\net40\FluentAssertions.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Newtonsoft.Json.5.0.6\lib\net40\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="nunit.framework">
<HintPath>..\packages\NUnit.2.6.2\lib\nunit.framework.dll</HintPath>
</Reference>
@ -65,9 +73,7 @@
<Name>NzbDrone.Test.Common</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Folder Include="Json\" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.

View File

@ -1,4 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="FluentAssertions" version="2.1.0.0" targetFramework="net40" />
<package id="Newtonsoft.Json" version="5.0.6" targetFramework="net40" />
<package id="NUnit" version="2.6.2" targetFramework="net40" />
</packages>

View File

@ -1,13 +1,13 @@
using Newtonsoft.Json;
using NzbDrone.Common.Serializer;
namespace NzbDrone.Test.Common
{
public static class ObjectExtentions
{
public static T JsonClone<T>(this T source)
public static T JsonClone<T>(this T source) where T : new()
{
var json = JsonConvert.SerializeObject(source);
return JsonConvert.DeserializeObject<T>(json);
var json = source.ToJson();
return Json.Deserialize<T>(json);
}
}
}