Skip to content

Commit 2c597d3

Browse files
authored
Try and convert from decimal to the underlying type value, if the type is nullable (#44)
This fixes the underlying problem in #32. Failing test is included.
1 parent 1016c4d commit 2c597d3

2 files changed

Lines changed: 15 additions & 5 deletions

File tree

SystemTextJsonPatch.Tests/IntegrationTests/PatchDocumentSerializationTest.cs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Text.Json;
2+
using System.Text.Json.Serialization;
23
using SystemTextJsonPatch.Exceptions;
34
using Xunit;
45

@@ -56,17 +57,21 @@ public void Test()
5657
{
5758
Class1 obj = new();
5859
var sourcePatch = new JsonPatchDocument<Class1>().Replace(c => c.Id, 1000);
59-
var deserializedPatchDoc = JsonSerializer.Deserialize<JsonPatchDocument<Class1>>(JsonSerializer.Serialize(sourcePatch));
60+
var patchJson = JsonSerializer.Serialize(sourcePatch);
61+
var deserializedPatchDoc = JsonSerializer.Deserialize(patchJson, Class1SerializerContext.Default.JsonPatchDocumentClass1);
6062

6163
sourcePatch.ApplyTo(obj); // success
6264
deserializedPatchDoc.ApplyTo(obj); // JsonPatchTestOperationException: The value '1000' is invalid for target location.
6365

6466
Assert.Equal(1000, obj.Id);
6567
}
68+
}
6669

67-
public class Class1
68-
{
69-
public int? Id { get; set; }
70-
}
70+
public class Class1
71+
{
72+
public int? Id { get; set; }
7173
}
74+
75+
[JsonSerializable(typeof(JsonPatchDocument<Class1>))]
76+
public sealed partial class Class1SerializerContext : JsonSerializerContext { }
7277
}

SystemTextJsonPatch/Internal/ConversionResultProvider.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,11 @@ internal static bool TryCopyTo(object? value, Type typeToConvertTo, JsonSerializ
108108
// fast-path for converting decimal to target types
109109
private static bool TryConvertDecimalToNumber(decimal decimalValue, Type typeToConvertTo, out object? convertedValue)
110110
{
111+
if (typeToConvertTo.IsGenericType && typeToConvertTo.GetGenericTypeDefinition() == typeof(Nullable<>))
112+
{
113+
typeToConvertTo = typeToConvertTo.GetGenericArguments()[0];
114+
}
115+
111116
switch (Type.GetTypeCode(typeToConvertTo))
112117
{
113118
case TypeCode.SByte:

0 commit comments

Comments
 (0)