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

Use System.Text.Json by default #1005

Merged
merged 4 commits into from
Nov 25, 2020
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
1 change: 1 addition & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)buildtask.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<DebugType>embedded</DebugType>
</PropertyGroup>

<PropertyGroup Condition="'$(TF_BUILD)' == 'true'">
Expand Down
2 changes: 1 addition & 1 deletion Refit.HttpClientFactory/HttpClientFactoryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public static IHttpClientBuilder AddRefitClient(this IServiceCollection services
.AddTypedClient(refitInterfaceType, (client, serviceProvider) => RestService.For(refitInterfaceType, client, settings));
}

private static IHttpClientBuilder AddTypedClient(this IHttpClientBuilder builder, Type type, Func<HttpClient, IServiceProvider, object> factory)
static IHttpClientBuilder AddTypedClient(this IHttpClientBuilder builder, Type type, Func<HttpClient, IServiceProvider, object> factory)
{
if (builder == null)
{
Expand Down
3 changes: 1 addition & 2 deletions Refit.HttpClientFactory/Refit.HttpClientFactory.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
<PropertyGroup>
<Product>Refit HTTP Client Factory Extensions</Product>
<Description>Refit HTTP Client Factory Extensions</Description>
<TargetFramework>netstandard2.0</TargetFramework>
<DebugType>embedded</DebugType>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
Expand All @@ -15,7 +17,7 @@ public sealed class NewtonsoftJsonContentSerializer : IContentSerializer
/// <summary>
/// The <see cref="Lazy{T}"/> instance providing the JSON serialization settings to use
/// </summary>
private readonly Lazy<JsonSerializerSettings> jsonSerializerSettings;
readonly Lazy<JsonSerializerSettings> jsonSerializerSettings;

/// <summary>
/// Creates a new <see cref="NewtonsoftJsonContentSerializer"/> instance
Expand Down Expand Up @@ -52,5 +54,15 @@ public async Task<T> DeserializeAsync<T>(HttpContent content)

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

public string GetFieldNameForProperty(PropertyInfo propertyInfo)
{
if (propertyInfo is null)
throw new ArgumentNullException(nameof(propertyInfo));

return propertyInfo.GetCustomAttributes<JsonPropertyAttribute>(true)
.Select(a => a.PropertyName)
.FirstOrDefault();
}
}
}
28 changes: 28 additions & 0 deletions Refit.Newtonsoft.Json/Refit.Newtonsoft.Json.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Product>Refit Serializer for Newtonsoft.Json ($(TargetFramework))</Product>
<Description>Refit Serializers for Newtonsoft.Json</Description>
<TargetFrameworks>netstandard2.0;netstandard2.1;net461</TargetFrameworks>
<GenerateDocumentationFile Condition=" '$(Configuration)' == 'Release' ">true</GenerateDocumentationFile>
<RootNamespace>Refit</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />

</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net461'">
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies"
Version="1.0.0"
PrivateAssets="All" />
<Reference Include="System.Web" />
<Reference Include="System.Net.Http" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Refit\Refit.csproj" />
</ItemGroup>

</Project>
5 changes: 4 additions & 1 deletion Refit.Tests/FormValueMultimapTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;

using Newtonsoft.Json;

Expand All @@ -10,7 +11,7 @@ namespace Refit.Tests
{
public class FormValueMultimapTests
{
readonly RefitSettings settings = new RefitSettings();
readonly RefitSettings settings = new();

[Fact]
public void EmptyIfNullPassedIn()
Expand Down Expand Up @@ -328,10 +329,12 @@ public class AliasingTestClass
public string Foo { get; set; }

[JsonProperty(PropertyName = "b")]
[JsonPropertyName("b")]
public string Bar { get; set; }

[AliasAs("a")]
[JsonProperty(PropertyName = "z")]
[JsonPropertyName("z")]
public string Baz { get; set; }


Expand Down
9 changes: 9 additions & 0 deletions Refit.Tests/GlobalSuppressions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.

using System.Diagnostics.CodeAnalysis;

[assembly: SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "<Pending>", Scope = "member", Target = "~T:Refit.Tests.RequestBuilderTests")]
[assembly: SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "<Pending>", Scope = "member", Target = "~T:Refit.Tests.MultipartTests")]
6 changes: 3 additions & 3 deletions Refit.Tests/MethodOverloads.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public async Task BasicMethodOverloadTest()

var resp = await fixture.Get(403);

Assert.True(!String.IsNullOrWhiteSpace(plainText));
Assert.True(!string.IsNullOrWhiteSpace(plainText));
Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode);

}
Expand Down Expand Up @@ -150,7 +150,7 @@ public async Task GenericMethodOverloadTest4()
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.WithHeaders("X-Refit", "99")
.WithQueryString("param", "foo")
.Respond("application/json", "{'url': 'https://httpbin.org/get', 'args': {'param': 'foo'}}");
.Respond("application/json", "{\"url\": \"https://httpbin.org/get\", \"args\": {\"param\": \"foo\"}}");

var fixture = RestService.For<IUseOverloadedGenericMethods<HttpBinGet, string, int>>("https://httpbin.org/", settings);

Expand All @@ -173,7 +173,7 @@ public async Task GenericMethodOverloadTest5()
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.WithHeaders("X-Refit", "foo")
.WithQueryString("param", "99")
.Respond("application/json", "{'url': 'https://httpbin.org/get', 'args': {'param': '99'}}");
.Respond("application/json", "{\"url\": \"https://httpbin.org/get\", \"args\": {\"param\": \"99\"}}");

var fixture = RestService.For<IUseOverloadedGenericMethods<HttpBinGet, string, int>>("https://httpbin.org/", settings);

Expand Down
18 changes: 13 additions & 5 deletions Refit.Tests/MultipartTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,19 @@ public async Task MultipartUploadShouldWorkWithHeaderAndRequestProperty()

var handler = new MockHttpMessageHandler
{
RequestAsserts = async message =>
RequestAsserts = message =>
{
Assert.Equal(someHeader, message.Headers.Authorization.ToString());

#if NET5_0
Assert.Single(message.Options);
Assert.Equal(someProperty, ((IDictionary<string, object>)message.Options)["SomeProperty"]);
#endif

#pragma warning disable CS0618 // Type or member is obsolete
Assert.Single(message.Properties);
Assert.Equal(someProperty, message.Properties["SomeProperty"]);
#pragma warning restore CS0618 // Type or member is obsolete
},
Asserts = async content =>
{
Expand Down Expand Up @@ -546,7 +554,7 @@ public async Task MultipartUploadShouldWorkWithFileInfoPart()
[InlineData(typeof(XmlContentSerializer), "application/xml")]
public async Task MultipartUploadShouldWorkWithAnObject(Type contentSerializerType, string mediaType)
{
if (!(Activator.CreateInstance(contentSerializerType) is IContentSerializer serializer))
if (Activator.CreateInstance(contentSerializerType) is not IContentSerializer serializer)
{
throw new ArgumentException($"{contentSerializerType.FullName} does not implement {nameof(IContentSerializer)}");
}
Expand Down Expand Up @@ -590,7 +598,7 @@ public async Task MultipartUploadShouldWorkWithAnObject(Type contentSerializerTy
[InlineData(typeof(XmlContentSerializer), "application/xml")]
public async Task MultipartUploadShouldWorkWithObjects(Type contentSerializerType, string mediaType)
{
if (!(Activator.CreateInstance(contentSerializerType) is IContentSerializer serializer))
if (Activator.CreateInstance(contentSerializerType) is not IContentSerializer serializer)
{
throw new ArgumentException($"{contentSerializerType.FullName} does not implement {nameof(IContentSerializer)}");
}
Expand Down Expand Up @@ -787,7 +795,7 @@ public void MultiPartConstructorShouldThrowArgumentNullExceptionWhenNoFileName()
{
Assert.Throws<ArgumentNullException>(() =>
{
var byteArrayPart = new ByteArrayPart(new byte[0], null, "application/pdf");
var byteArrayPart = new ByteArrayPart(Array.Empty<byte>(), null, "application/pdf");
});
}

Expand Down Expand Up @@ -831,7 +839,7 @@ internal static Stream GetTestFileStream(string relativeFilePath)
return stream;
}

bool StreamsEqual(Stream a, Stream b)
static bool StreamsEqual(Stream a, Stream b)
{
if (a == null &&
b == null)
Expand Down
2 changes: 1 addition & 1 deletion Refit.Tests/Refit.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<PackageReference Include="RichardSzalay.MockHttp" Version="6.0.0" />
<ProjectReference Include="..\InterfaceStubGenerator.App\InterfaceStubGenerator.App.csproj" />
<ProjectReference Include="..\Refit.HttpClientFactory\Refit.HttpClientFactory.csproj" />
<ProjectReference Include="..\Refit\Refit.csproj" />
<ProjectReference Include="..\Refit.Newtonsoft.Json\Refit.Newtonsoft.Json.csproj" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net461' ">
Expand Down
5 changes: 3 additions & 2 deletions Refit.Tests/RefitStubs.Net46.cs
Original file line number Diff line number Diff line change
Expand Up @@ -532,9 +532,9 @@ Task IApiBindPathToObject.GetFoos(PathBoundList request)
}

/// <inheritdoc />
Task IApiBindPathToObject.GetFoos2(List<int> Values)
Task IApiBindPathToObject.GetFoos2(List<int> values)
{
var arguments = new object[] { Values };
var arguments = new object[] { values };
var func = requestBuilder.BuildRestResultFuncForMethod("GetFoos2", new Type[] { typeof(List<int>) });
return (Task)func(Client, arguments);
}
Expand Down Expand Up @@ -1857,6 +1857,7 @@ namespace Refit.Tests
using global::Refit.Buffers;
using global::Xunit;
using JsonSerializer = global::Newtonsoft.Json.JsonSerializer;
using global::System.Text.Json.Serialization;

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
Expand Down
5 changes: 3 additions & 2 deletions Refit.Tests/RefitStubs.Net5.cs
Original file line number Diff line number Diff line change
Expand Up @@ -532,9 +532,9 @@ Task IApiBindPathToObject.GetFoos(PathBoundList request)
}

/// <inheritdoc />
Task IApiBindPathToObject.GetFoos2(List<int> Values)
Task IApiBindPathToObject.GetFoos2(List<int> values)
{
var arguments = new object[] { Values };
var arguments = new object[] { values };
var func = requestBuilder.BuildRestResultFuncForMethod("GetFoos2", new Type[] { typeof(List<int>) });
return (Task)func(Client, arguments);
}
Expand Down Expand Up @@ -1857,6 +1857,7 @@ namespace Refit.Tests
using global::Refit.Buffers;
using global::Xunit;
using JsonSerializer = global::Newtonsoft.Json.JsonSerializer;
using global::System.Text.Json.Serialization;

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
Expand Down
5 changes: 3 additions & 2 deletions Refit.Tests/RefitStubs.NetCore2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -532,9 +532,9 @@ Task IApiBindPathToObject.GetFoos(PathBoundList request)
}

/// <inheritdoc />
Task IApiBindPathToObject.GetFoos2(List<int> Values)
Task IApiBindPathToObject.GetFoos2(List<int> values)
{
var arguments = new object[] { Values };
var arguments = new object[] { values };
var func = requestBuilder.BuildRestResultFuncForMethod("GetFoos2", new Type[] { typeof(List<int>) });
return (Task)func(Client, arguments);
}
Expand Down Expand Up @@ -1857,6 +1857,7 @@ namespace Refit.Tests
using global::Refit.Buffers;
using global::Xunit;
using JsonSerializer = global::Newtonsoft.Json.JsonSerializer;
using global::System.Text.Json.Serialization;

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
Expand Down
5 changes: 3 additions & 2 deletions Refit.Tests/RefitStubs.NetCore3.cs
Original file line number Diff line number Diff line change
Expand Up @@ -532,9 +532,9 @@ Task IApiBindPathToObject.GetFoos(PathBoundList request)
}

/// <inheritdoc />
Task IApiBindPathToObject.GetFoos2(List<int> Values)
Task IApiBindPathToObject.GetFoos2(List<int> values)
{
var arguments = new object[] { Values };
var arguments = new object[] { values };
var func = requestBuilder.BuildRestResultFuncForMethod("GetFoos2", new Type[] { typeof(List<int>) });
return (Task)func(Client, arguments);
}
Expand Down Expand Up @@ -1857,6 +1857,7 @@ namespace Refit.Tests
using global::Refit.Buffers;
using global::Xunit;
using JsonSerializer = global::Newtonsoft.Json.JsonSerializer;
using global::System.Text.Json.Serialization;

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
Expand Down
Loading