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

[release/5.0-rc2] Add JsonNumberHandling.AllowReadingFromString as a JsonSerializer web default (#41539) #42240

Merged
merged 1 commit into from
Sep 15, 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
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ public sealed partial class JsonContent : HttpContent
private static MediaTypeHeaderValue DefaultMediaType
=> new MediaTypeHeaderValue(JsonMediaType) { CharSet = "utf-8" };

internal static readonly JsonSerializerOptions s_defaultSerializerOptions
= new JsonSerializerOptions { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
internal static readonly JsonSerializerOptions s_defaultSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);

private readonly JsonSerializerOptions? _jsonSerializerOptions;
public Type ObjectType { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ namespace System.Net.Http.Json.Functional.Tests
{
public class HttpClientJsonExtensionsTests
{
[Fact]
public async Task TestGetFromJsonAsync()
[Theory]
[MemberData(nameof(ReadFromJsonTestData))]
public async Task TestGetFromJsonAsync(string json)
{
string json = Person.Create().Serialize();
HttpHeaderData header = new HttpHeaderData("Content-Type", "application/json");
List<HttpHeaderData> headers = new List<HttpHeaderData> { header };

Expand All @@ -41,6 +41,13 @@ await HttpMessageHandlerLoopbackServer.CreateClientAndServerAsync(
server => server.HandleRequestAsync(content: json, headers: headers));
}

public static IEnumerable<object[]> ReadFromJsonTestData()
{
Person per = Person.Create();
yield return new object[] { per.Serialize() };
yield return new object[] { per.SerializeWithNumbersAsStrings() };
}

[Fact]
public async Task TestGetFromJsonAsyncUnsuccessfulResponseAsync()
{
Expand Down Expand Up @@ -114,7 +121,14 @@ await HttpMessageHandlerLoopbackServer.CreateClientAndServerAsync(
async server => {
HttpRequestData request = await server.HandleRequestAsync();
ValidateRequest(request);
Person obj = JsonSerializer.Deserialize<Person>(request.Body, JsonOptions.DefaultSerializerOptions);

byte[] json = request.Body;

Person obj = JsonSerializer.Deserialize<Person>(json, JsonOptions.DefaultSerializerOptions);
obj.Validate();

// Assert numbers are not written as strings - JsonException would be thrown here if written as strings.
obj = JsonSerializer.Deserialize<Person>(json, JsonOptions.DefaultSerializerOptions_StrictNumberHandling);
obj.Validate();
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ public void ThrowOnNull()
AssertExtensions.Throws<ArgumentNullException>("content", () => content.ReadFromJsonAsync(typeof(Person)));
}

[Fact]
public async Task HttpContentGetThenReadFromJsonAsync()
[Theory]
[MemberData(nameof(ReadFromJsonTestData))]
public async Task HttpContentGetThenReadFromJsonAsync(string json)
{
await HttpMessageHandlerLoopbackServer.CreateClientAndServerAsync(
async (handler, uri) =>
Expand All @@ -42,7 +43,14 @@ await HttpMessageHandlerLoopbackServer.CreateClientAndServerAsync(
per.Validate();
}
},
server => server.HandleRequestAsync(headers: _headers, content: Person.Create().Serialize()));
server => server.HandleRequestAsync(headers: _headers, content: json));
}

public static IEnumerable<object[]> ReadFromJsonTestData()
{
Person per = Person.Create();
yield return new object[] { per.Serialize() };
yield return new object[] { per.SerializeWithNumbersAsStrings() };
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;
using Xunit;
Expand Down Expand Up @@ -32,16 +31,23 @@ public string Serialize(JsonSerializerOptions options = null)
{
return JsonSerializer.Serialize(this, options);
}

public string SerializeWithNumbersAsStrings(JsonSerializerOptions options = null)
{
options ??= new JsonSerializerOptions();
options.NumberHandling = options.NumberHandling | JsonNumberHandling.WriteAsString;
return JsonSerializer.Serialize(this, options);
}
}

internal static class JsonOptions
{
public static readonly JsonSerializerOptions DefaultSerializerOptions
= new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
public static readonly JsonSerializerOptions DefaultSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);

public static readonly JsonSerializerOptions DefaultSerializerOptions_StrictNumberHandling = new JsonSerializerOptions(DefaultSerializerOptions)
{
NumberHandling = JsonNumberHandling.Strict
};
}

internal class EnsureDefaultOptionsConverter : JsonConverter<EnsureDefaultOptions>
Expand All @@ -68,7 +74,8 @@ public override void Write(Utf8JsonWriter writer, EnsureDefaultOptions value, Js
private static void AssertDefaultOptions(JsonSerializerOptions options)
{
Assert.True(options.PropertyNameCaseInsensitive);
Assert.Equal(JsonNamingPolicy.CamelCase, options.PropertyNamingPolicy);
Assert.Same(JsonNamingPolicy.CamelCase, options.PropertyNamingPolicy);
Assert.Equal(JsonNumberHandling.AllowReadingFromString, options.NumberHandling);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public enum JsonSerializerDefaults
/// Specifies that values should be used more appropriate to web-based scenarios.
/// </summary>
/// <remarks>
/// This option implies that property names are treated as case-insensitive and that "camelCase" name formatting should be employed.
/// This option implies that property names are treated as case-insensitive, "camelCase" name formatting should be employed, and that numbers can be read from JSON strings.
/// </remarks>
Web = 1
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ public JsonSerializerOptions(JsonSerializerDefaults defaults) : this()
{
_propertyNameCaseInsensitive = true;
_jsonPropertyNamingPolicy = JsonNamingPolicy.CamelCase;
_numberHandling = JsonNumberHandling.AllowReadingFromString;
}
else if (defaults != JsonSerializerDefaults.General)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -533,9 +533,9 @@ public static void DefaultSerializerOptions_General()
public static void PredefinedSerializerOptions_Web()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
JsonNamingPolicy policy = options.PropertyNamingPolicy;
Assert.True(options.PropertyNameCaseInsensitive);
Assert.Same(JsonNamingPolicy.CamelCase, policy);
Assert.Same(JsonNamingPolicy.CamelCase, options.PropertyNamingPolicy);
Assert.Equal(JsonNumberHandling.AllowReadingFromString, options.NumberHandling);
}

[Theory]
Expand Down