Skip to content

Commit 7bd1772

Browse files
CopiloteNeRGy164
andcommitted
Fix ReturnType property deserialization in System.Text.Json (#4)
* Fix ReturnType property deserialization by using CanWrite check Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: eNeRGy164 <[email protected]>
1 parent 1b301ce commit 7bd1772

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/DendroDocs.Shared/Json/JsonDefaults.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,11 @@ void SetDefaultValues(object obj)
123123
var defaultValueAttribute = reflectedProperty.GetCustomAttribute<DefaultValueAttribute>();
124124
if (defaultValueAttribute is not null)
125125
{
126+
if (!reflectedProperty.CanWrite)
127+
{
128+
continue;
129+
}
130+
126131
// Check if not already set, e.g. by a property initializer
127132
if (!Equals(reflectedProperty.GetValue(obj), defaultValueAttribute.Value))
128133
{

tests/DendroDocs.Shared.Tests/Serialization/TextJsonDeserializationTests.cs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,4 +408,51 @@ public void AStatementInASwitchSectionShouldHaveTheSwitchSectionAsParent()
408408
var @switch = (Switch)types[0].Methods[0].Statements[0];
409409
@switch.Sections[0].Statements[0].Parent.ShouldBe(@switch.Sections[0]);
410410
}
411+
412+
[TestMethod]
413+
public void MethodWithReturnTypeInJson_Should_DeserializeCorrectly()
414+
{
415+
// Assign
416+
var json =
417+
"""
418+
[{
419+
"FullName": "Test.Class",
420+
"Methods": [{
421+
"Name": "GetAllAsync",
422+
"ReturnType": "System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.IActionResult>"
423+
}]
424+
}]
425+
""";
426+
427+
// Act
428+
var types = JsonSerializer.Deserialize<List<TypeDescription>>(json, JsonDefaults.DeserializerOptions())!;
429+
430+
// Assert
431+
types[0].Methods.Count.ShouldBe(1);
432+
types[0].Methods[0].Name.ShouldBe("GetAllAsync");
433+
types[0].Methods[0].ReturnType.ShouldBe("System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.IActionResult>");
434+
}
435+
436+
[TestMethod]
437+
public void MethodWithoutReturnTypeInJson_Should_DefaultToVoid()
438+
{
439+
// Assign
440+
var json =
441+
"""
442+
[{
443+
"FullName": "Test.Class",
444+
"Methods": [{
445+
"Name": "VoidMethod"
446+
}]
447+
}]
448+
""";
449+
450+
// Act
451+
var types = JsonSerializer.Deserialize<List<TypeDescription>>(json, JsonDefaults.DeserializerOptions())!;
452+
453+
// Assert
454+
types[0].Methods.Count.ShouldBe(1);
455+
types[0].Methods[0].Name.ShouldBe("VoidMethod");
456+
types[0].Methods[0].ReturnType.ShouldBe("void");
457+
}
411458
}

0 commit comments

Comments
 (0)