Skip to content

Commit 1016c4d

Browse files
authored
Support assigning null to non-reference types when HandleNull converter is registered (#46)
1 parent b046f06 commit 1016c4d

2 files changed

Lines changed: 48 additions & 3 deletions

File tree

SystemTextJsonPatch.Tests/JsonPatchDocumentJsonObjectTest.cs

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
using System.Linq;
1+
using System;
2+
using System.Linq;
23
using System.Text.Json;
34
using System.Text.Json.Nodes;
5+
using System.Text.Json.Serialization;
46
using SystemTextJsonPatch.Exceptions;
57
using SystemTextJsonPatch.Operations;
68
using Xunit;
@@ -328,6 +330,46 @@ public void ApplyToModelReplaceNull()
328330
Assert.Null(model.CustomData["Email"]);
329331
}
330332

333+
[Fact]
334+
public void ApplyToModelReplaceNonReferenceWithNull()
335+
{
336+
// Arrange
337+
var model = new SimpleObject { IntegerValue = 123 };
338+
var patch = new JsonPatchDocument<SimpleObject>()
339+
{
340+
Options = new() { Converters = { new IntJsonConverter() } },
341+
};
342+
343+
patch.Operations.Add(new Operation<SimpleObject>("replace", "/IntegerValue", null, null));
344+
345+
// Act
346+
patch.ApplyTo(model);
347+
348+
// Assert
349+
Assert.Equal(999, model.IntegerValue);
350+
}
351+
352+
class IntJsonConverter : JsonConverter<int>
353+
{
354+
public override bool HandleNull { get; } = true;
355+
356+
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options
357+
)
358+
{
359+
if (reader.TokenType == JsonTokenType.Null)
360+
{
361+
return 999;
362+
}
363+
364+
return reader.GetInt32();
365+
}
366+
367+
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
368+
{
369+
writer.WriteNumberValue(value);
370+
}
371+
}
372+
331373
[Fact]
332374
public void ApplyToModelReplaceWithIgnoringCasing()
333375
{

SystemTextJsonPatch/Internal/ConversionResultProvider.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,11 @@ internal static bool TryConvertTo(object? value, Type typeToConvertTo, JsonSeria
1616

1717
if (value == null)
1818
{
19-
convertedValue = null;
20-
return IsNullableType(typeToConvertTo);
19+
if (IsNullableType(typeToConvertTo))
20+
{
21+
convertedValue = null;
22+
return true;
23+
}
2124
}
2225

2326
if (typeToConvertTo.IsInstanceOfType(value))

0 commit comments

Comments
 (0)