Skip to content

JsonSerializer throws AccessViolationException for struct with field initializers #62983

@yufeih

Description

@yufeih

Description

Deserialize a struct with field initializer causes AccessViolationException .

Reproduction Steps

JsonSerializer.Deserialize<Foo>("{}");

public struct Foo
{
    public float A = 1;
}

Expected behavior

The struct is deserialized successfully with the field initialized using the default field initializer.

Actual behavior

Throws this exception:

Fatal error. System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at System.Runtime.CompilerServices.CastHelpers.IsInstanceOfInterface(Void*, System.Object)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1[[Foo, console, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].OnTryRead(System.Text.Json.Utf8JsonReader ByRef, System.Type, System.Text.Json.JsonSerializerOptions, System.Text.Json.ReadStack ByRef, Foo ByRef)
   at System.Text.Json.Serialization.JsonConverter`1[[Foo, console, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].TryRead(System.Text.Json.Utf8JsonReader ByRef, System.Type, System.Text.Json.JsonSerializerOptions, System.Text.Json.ReadStack ByRef, Foo ByRef)
   at System.Text.Json.Serialization.JsonConverter`1[[Foo, console, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(System.Text.Json.Utf8JsonReader ByRef, System.Text.Json.JsonSerializerOptions, System.Text.Json.ReadStack ByRef)
   at System.Text.Json.JsonSerializer.ReadFromSpan[[Foo, console, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]](System.ReadOnlySpan`1<Byte>, System.Text.Json.Serialization.Metadata.JsonTypeInfo, System.Nullable`1<Int32>)
   at System.Text.Json.JsonSerializer.ReadFromSpan[[Foo, console, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]](System.ReadOnlySpan`1<Char>, System.Text.Json.Serialization.Metadata.JsonTypeInfo)
   at System.Text.Json.JsonSerializer.Deserialize[[Foo, console, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]](System.String, System.Text.Json.JsonSerializerOptions)
   at Program.<Main>$(System.String[])

Regression?

No response

Known Workarounds

No response

Configuration

.NET SDK Version: 6.0.101

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions