Skip to content
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 @@ -49,6 +49,11 @@ internal sealed class ReflectionEmitMemberAccessor : MemberAccessor
else
{
generator.Emit(OpCodes.Newobj, realMethod);
if (type.IsValueType)
{
// Since C# 10 it's now possible to have parameterless constructors in structs
generator.Emit(OpCodes.Box, type);
}
}

generator.Emit(OpCodes.Ret);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1322,5 +1322,68 @@ public class ClassWithIgnoredSameType

public ClassWithIgnoredSameType(ClassWithIgnoredSameType prop) { }
}

[Fact]
public void StructWithPropertyInit_DeseralizeEmptyObject()
{
string json = @"{}";
var obj = JsonSerializer.Deserialize<StructWithPropertyInit>(json);
Assert.Equal(42, obj.A);
Assert.Equal(0, obj.B);
}

[Fact]
public void StructWithPropertyInit_OverrideInitedProperty()
{
string json = @"{""A"":43}";
var obj = JsonSerializer.Deserialize<StructWithPropertyInit>(json);
Assert.Equal(43, obj.A);
Assert.Equal(0, obj.B);

json = @"{""A"":0,""B"":44}";
obj = JsonSerializer.Deserialize<StructWithPropertyInit>(json);
Assert.Equal(0, obj.A);
Assert.Equal(44, obj.B);

json = @"{""B"":45}";
obj = JsonSerializer.Deserialize<StructWithPropertyInit>(json);
Assert.Equal(42, obj.A); // JSON doesn't set A property so it's expected to be 42
Assert.Equal(45, obj.B);
}

public struct StructWithPropertyInit
{
public long A { get; set; } = 42;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consider for completeness one more test where you explicitly set this to something else (i.e. 43) in the JSON and make sure this got respected

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added!

public long B { get; set; }
}

[Fact]
public void StructWithFieldInit_DeseralizeEmptyObject()
{
string json = @"{}";
var obj = JsonSerializer.Deserialize<StructWithFieldInit>(json);
Assert.Equal(0, obj.A);
Assert.Equal(42, obj.B);
}

public struct StructWithFieldInit
{
public long A;
public long B = 42;
}

[Fact]
public void StructWithExplicitParameterlessCtor_DeseralizeEmptyObject()
{
string json = @"{}";
var obj = JsonSerializer.Deserialize<StructWithExplicitParameterlessCtor>(json);
Assert.Equal(42, obj.A);
}

public struct StructWithExplicitParameterlessCtor
{
public long A;
public StructWithExplicitParameterlessCtor() => A = 42;
}
}
}