Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor serialization into own class #373

Merged
merged 2 commits into from
Apr 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions TMDbLib/Client/TMDbClient.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
using System;
using Newtonsoft.Json;
using TMDbLib.Objects.Account;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.General;
using TMDbLib.Utilities.Converters;
using ParameterType = TMDbLib.Rest.ParameterType;
using RestClient = TMDbLib.Rest.RestClient;
using RestRequest = TMDbLib.Rest.RestRequest;
Expand All @@ -12,6 +10,7 @@
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Rest;
using TMDbLib.Utilities.Serializer;

namespace TMDbLib.Client
{
Expand All @@ -20,23 +19,17 @@ public partial class TMDbClient : IDisposable
private const string ApiVersion = "3";
private const string ProductionUrl = "api.themoviedb.org";

private readonly JsonSerializer _serializer;
private readonly ITMDbSerializer _serializer;
private RestClient _client;
private TMDbConfig _config;

public TMDbClient(string apiKey, bool useSsl = true, string baseUrl = ProductionUrl, JsonSerializer serializer = null, IWebProxy proxy = null)
public TMDbClient(string apiKey, bool useSsl = true, string baseUrl = ProductionUrl, ITMDbSerializer serializer = null, IWebProxy proxy = null)
{
DefaultLanguage = null;
DefaultImageLanguage = null;
DefaultCountry = null;

_serializer = serializer ?? JsonSerializer.CreateDefault();
_serializer.Converters.Add(new ChangeItemConverter());
_serializer.Converters.Add(new AccountStateConverter());
_serializer.Converters.Add(new KnownForConverter());
_serializer.Converters.Add(new SearchBaseConverter());
_serializer.Converters.Add(new TaggedImageConverter());
_serializer.Converters.Add(new TolerantEnumConverter());
_serializer = serializer ?? TMDbJsonSerializer.Instance;

//Setup proxy to use during requests
//Proxy is optional. If passed, will be used in every request.
Expand Down
3 changes: 1 addition & 2 deletions TMDbLib/Objects/Changes/ChangeItemAdded.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TMDbLib.Objects.Changes
{
Expand All @@ -11,6 +10,6 @@ public ChangeItemAdded()
}

[JsonProperty("value")]
public JToken Value { get; set; }
public object Value { get; set; }
}
}
3 changes: 1 addition & 2 deletions TMDbLib/Objects/Changes/ChangeItemDeleted.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TMDbLib.Objects.Changes
{
Expand All @@ -11,6 +10,6 @@ public ChangeItemDeleted()
}

[JsonProperty("original_value")]
public JToken OriginalValue { get; set; }
public object OriginalValue { get; set; }
}
}
3 changes: 1 addition & 2 deletions TMDbLib/Objects/Changes/ChangeItemDestroyed.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TMDbLib.Objects.Changes
{
Expand All @@ -11,6 +10,6 @@ public ChangeItemDestroyed()
}

[JsonProperty("value")]
public JToken Value { get; set; }
public object Value { get; set; }
}
}
5 changes: 2 additions & 3 deletions TMDbLib/Objects/Changes/ChangeItemUpdated.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TMDbLib.Objects.Changes
{
Expand All @@ -11,9 +10,9 @@ public ChangeItemUpdated()
}

[JsonProperty("original_value")]
public JToken OriginalValue { get; set; }
public object OriginalValue { get; set; }

[JsonProperty("value")]
public JToken Value { get; set; }
public object Value { get; set; }
}
}
6 changes: 3 additions & 3 deletions TMDbLib/Rest/RestClient.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using TMDbLib.Utilities.Serializer;

namespace TMDbLib.Rest
{
internal class RestClient : IDisposable
{
private int _maxRetryCount;

public RestClient(Uri baseUrl, JsonSerializer serializer, IWebProxy proxy = null)
public RestClient(Uri baseUrl, ITMDbSerializer serializer, IWebProxy proxy = null)
{
BaseUrl = baseUrl;
Serializer = serializer;
Expand Down Expand Up @@ -52,7 +52,7 @@ public int MaxRetryCount

public bool ThrowApiExceptions { get; set; }

internal JsonSerializer Serializer { get; }
internal ITMDbSerializer Serializer { get; }

public void AddDefaultQueryString(string key, string value)
{
Expand Down
16 changes: 3 additions & 13 deletions TMDbLib/Rest/RestRequest.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
Expand All @@ -10,6 +9,7 @@
using System.Threading.Tasks;
using Newtonsoft.Json;
using TMDbLib.Objects.Exceptions;
using TMDbLib.Utilities.Serializer;

namespace TMDbLib.Rest
{
Expand Down Expand Up @@ -159,19 +159,9 @@ private HttpRequestMessage PrepRequest(HttpMethod method)
// Body
if (method == HttpMethod.Post && _bodyObj != null)
{
#pragma warning disable IDISP001 // Dispose created. => Stream is used in HttpContent
MemoryStream ms = new MemoryStream();
#pragma warning restore IDISP001 // Dispose created.
byte[] bodyBytes = _client.Serializer.SerializeToBytes(_bodyObj);

using (StreamWriter sw = new StreamWriter(ms, _client.Encoding, 4096, true))
using (JsonTextWriter tw = new JsonTextWriter(sw))
{
_client.Serializer.Serialize(tw, _bodyObj);
}

ms.Seek(0, SeekOrigin.Begin);

req.Content = new StreamContent(ms);
req.Content = new ByteArrayContent(bodyBytes);
req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}

Expand Down
8 changes: 3 additions & 5 deletions TMDbLib/Rest/RestResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TMDbLib.Utilities.Serializer;

namespace TMDbLib.Rest
{
Expand Down Expand Up @@ -43,11 +43,9 @@ public RestResponse(HttpResponseMessage response, RestClient client)

public async Task<T> GetDataObject()
{
Stream content = await GetContent().ConfigureAwait(false);
using Stream content = await GetContent().ConfigureAwait(false);

using (StreamReader sr = new StreamReader(content, _client.Encoding))
using (JsonTextReader tr = new JsonTextReader(sr))
return _client.Serializer.Deserialize<T>(tr);
return _client.Serializer.Deserialize<T>(content);
}
}
}
2 changes: 1 addition & 1 deletion TMDbLib/TMDbLib.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" PrivateAssets="compile" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net45' ">
Expand Down
11 changes: 11 additions & 0 deletions TMDbLib/Utilities/Serializer/ITMDbSerializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;
using System.IO;

namespace TMDbLib.Utilities.Serializer
{
public interface ITMDbSerializer
{
void Serialize(Stream target, object obj, Type type);
object Deserialize(Stream source, Type type);
}
}
59 changes: 59 additions & 0 deletions TMDbLib/Utilities/Serializer/SerializerExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System;
using System.IO;
using System.Text;

namespace TMDbLib.Utilities.Serializer
{
public static class SerializerExtensions
{
public static void Serialize<T>(this ITMDbSerializer serializer, Stream target, T @object)
{
serializer.Serialize(target, @object, typeof(T));
}

public static byte[] SerializeToBytes<T>(this ITMDbSerializer serializer, T @object)
{
using MemoryStream ms = new MemoryStream();

serializer.Serialize(ms, @object, typeof(T));

return ms.ToArray();
}

public static string SerializeToString<T>(this ITMDbSerializer serializer, T @object)
{
using MemoryStream ms = new MemoryStream();

serializer.Serialize(ms, @object, typeof(T));

ms.Seek(0, SeekOrigin.Begin);

using StreamReader sr = new StreamReader(ms, Encoding.UTF8);

return sr.ReadToEnd();
}

public static T Deserialize<T>(this ITMDbSerializer serializer, Stream source)
{
return (T)serializer.Deserialize(source, typeof(T));
}

public static T DeserializeFromString<T>(this ITMDbSerializer serializer, string json)
{
// TODO: Better method
byte[] bytes = Encoding.UTF8.GetBytes(json);
using MemoryStream ms = new MemoryStream(bytes);

return serializer.Deserialize<T>(ms);
}

public static object DeserializeFromString(this ITMDbSerializer serializer, string json, Type type)
{
// TODO: Better method
byte[] bytes = Encoding.UTF8.GetBytes(json);
using MemoryStream ms = new MemoryStream(bytes);

return serializer.Deserialize(ms, type);
}
}
}
43 changes: 43 additions & 0 deletions TMDbLib/Utilities/Serializer/TMDbJsonSerializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using TMDbLib.Utilities.Converters;

namespace TMDbLib.Utilities.Serializer
{
public class TMDbJsonSerializer : ITMDbSerializer
{
private readonly JsonSerializer _serializer;
private readonly Encoding _encoding = new UTF8Encoding(false);

public static TMDbJsonSerializer Instance { get; } = new();

private TMDbJsonSerializer()
{
_serializer = JsonSerializer.CreateDefault();
_serializer.Converters.Add(new ChangeItemConverter());
_serializer.Converters.Add(new AccountStateConverter());
_serializer.Converters.Add(new KnownForConverter());
_serializer.Converters.Add(new SearchBaseConverter());
_serializer.Converters.Add(new TaggedImageConverter());
_serializer.Converters.Add(new TolerantEnumConverter());
}

public void Serialize(Stream target, object obj, Type type)
{
using StreamWriter sw = new StreamWriter(target, _encoding, 4096, true);
using JsonTextWriter jw = new JsonTextWriter(sw);

_serializer.Serialize(jw, obj, type);
}

public object Deserialize(Stream source, Type type)
{
using StreamReader sr = new StreamReader(source, _encoding, false, 4096, true);
using JsonTextReader jr = new JsonTextReader(sr);

return _serializer.Deserialize(jr, type);
}
}
}
1 change: 1 addition & 0 deletions TMDbLibTests/ClientAccountTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xunit;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.General;
Expand Down
1 change: 1 addition & 0 deletions TMDbLibTests/ClientAuthenticationTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TMDbLibTests.Exceptions;
using Xunit;
using TMDbLib.Objects.Authentication;
Expand Down
15 changes: 7 additions & 8 deletions TMDbLibTests/JsonHelpers/TestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using TMDbLib.Client;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Utilities.Serializer;
using TMDbLibTests.Helpers;
using VerifyTests;
using VerifyXunit;
Expand All @@ -27,10 +27,11 @@ public abstract class TestBase

protected TMDbClient TMDbClient => TestConfig.Client;

protected ITMDbSerializer Serializer => TMDbJsonSerializer.Instance;

protected TestBase()
{
VerifySettings = new VerifySettings();
//VerifySettings.UseExtension("json");
//VerifySettings.AutoVerify();

VerifySettings.UseDirectory("..\\Verification");
Expand All @@ -48,12 +49,10 @@ protected TestBase()
serializerSettings.ContractResolver = new DataSortingContractResolver(serializerSettings.ContractResolver);
});

JsonSerializerSettings sett = new JsonSerializerSettings();

WebProxy proxy = null;
//WebProxy proxy = new WebProxy("http://127.0.0.1:8888");

TestConfig = new TestConfig(serializer: JsonSerializer.Create(sett), proxy: proxy);
TestConfig = new TestConfig(serializer: null, proxy: proxy);
}

protected Task Verify<T>(T obj, Action<VerifySettings> configure = null)
Expand Down Expand Up @@ -141,10 +140,10 @@ private void SerializingCallback(object obj, StreamingContext context)

private static bool IsSorted(IList list, IComparer comparer)
{
for (var i = 1; i < list.Count; i++)
for (int i = 1; i < list.Count; i++)
{
var a = list[i - 1];
var b = list[i];
object a = list[i - 1];
object b = list[i];

if (comparer.Compare(a, b) > 0)
return false;
Expand Down
Loading