Spotify.NET/SpotifyAPI.Web/Http/NewtonsoftJSONSerializer.cs

69 lines
2.0 KiB
C#
Raw Normal View History

2020-05-01 19:05:28 +01:00
using System;
2022-11-27 12:29:35 +00:00
using System.Collections.Generic;
2020-05-01 19:05:28 +01:00
using System.IO;
using System.Net.Http;
2022-11-27 12:29:35 +00:00
using System.Reflection;
2020-05-01 19:05:28 +01:00
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace SpotifyAPI.Web.Http
{
public class NewtonsoftJSONSerializer : IJSONSerializer
{
private readonly JsonSerializerSettings _serializerSettings;
2020-05-01 19:05:28 +01:00
public NewtonsoftJSONSerializer()
{
var contractResolver = new PrivateFieldDefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
2020-05-01 19:05:28 +01:00
_serializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = contractResolver
2020-05-01 19:05:28 +01:00
};
}
public IAPIResponse<T> DeserializeResponse<T>(IResponse response)
{
Ensure.ArgumentNotNull(response, nameof(response));
2020-05-25 17:00:38 +01:00
if (
(
response.ContentType?.Equals("application/json", StringComparison.Ordinal) is true || response.ContentType == null
))
2020-05-01 19:05:28 +01:00
{
2020-05-25 17:00:38 +01:00
var body = JsonConvert.DeserializeObject<T>(response.Body as string ?? "", _serializerSettings);
return new APIResponse<T>(response, body!);
2020-05-01 19:05:28 +01:00
}
return new APIResponse<T>(response);
}
public void SerializeRequest(IRequest request)
{
Ensure.ArgumentNotNull(request, nameof(request));
if (request.Body is string || request.Body is Stream || request.Body is HttpContent || request.Body is null)
{
return;
}
request.Body = JsonConvert.SerializeObject(request.Body, _serializerSettings);
}
private class PrivateFieldDefaultContractResolver : DefaultContractResolver
{
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
// Does not seem to work, still need DefaultMembersSearchFlags |= BindingFlags.NonPublic
var list = base.GetSerializableMembers(objectType);
list.AddRange(objectType.GetProperties(BindingFlags.NonPublic));
return list;
}
}
2020-05-01 19:05:28 +01:00
}
}