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

Support deserializing string to numeric values #16060

Merged
merged 3 commits into from
May 14, 2024
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
3 changes: 2 additions & 1 deletion src/OrchardCore/OrchardCore.Abstractions/Json/JOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ public static class JOptions
ReadCommentHandling = JsonCommentHandling.Skip,
PropertyNameCaseInsensitive = true,
AllowTrailingCommas = true,
WriteIndented = false
WriteIndented = false,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
};

public static readonly JsonSerializerOptions Default;
Expand Down
18 changes: 18 additions & 0 deletions test/OrchardCore.Tests/Serializers/JsonSerializerTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Json;
using OrchardCore.ContentFields.Settings;
using OrchardCore.Tests.Apis.Context;
using OrchardCore.Users.Core.Json;
using OrchardCore.Users.Indexes;
Expand Down Expand Up @@ -28,6 +29,18 @@ public void Deserialize_WhenCalled_ReturnValidUserLoginInfo()
Assert.Equal("default", obj.ProviderDisplayName);
}

[Theory]
[InlineData("{\"name\":\"One\",\"value\":\"1\",\"Weight\":\"1.75\"}", 1.75)]
[InlineData("{\"name\":\"One\",\"value\":\"1\",\"Weight\":\"1\"}", 1)]
[InlineData("{\"name\":\"One\",\"value\":\"1\",\"Weight\":1}", 1)]
[InlineData("{\"name\":\"One\",\"value\":\"1\",\"Weight\":2.75}", 2.75)]
public void Deserialize_WhenCalled_ReturnDoubleFromStringWithBaseOptions(string json, double expectedWeight)
{
var item = JsonSerializer.Deserialize<CustomListValueOption>(json, JOptions.Base);
MikeAlhayek marked this conversation as resolved.
Show resolved Hide resolved

Assert.Equal(expectedWeight, item.Weight);
MikeAlhayek marked this conversation as resolved.
Show resolved Hide resolved
}

[Fact]
public void Serialize_WhenCalled_ReturnValidJson()
{
Expand Down Expand Up @@ -74,4 +87,9 @@ await context.UsingTenantScopeAsync(async scope =>
Assert.Equal(loginInfo.ProviderDisplayName, userLoginInfo.ProviderDisplayName);
});
}

public sealed class CustomListValueOption : ListValueOption
{
public double? Weight { get; set; }
}
}