Skip to content

JsonConverter for {ReadOnly}Memory doesn't deserialize nulls #95267

@stephentoub

Description

@stephentoub

Given that this code runs successfully without exception or assert:

using System.Diagnostics;
using System.Text.Json;

ReadOnlyMemory<float> rom;

rom = default;
Debug.Assert(rom.IsEmpty);

rom = null;
Debug.Assert(rom.IsEmpty);

rom = (ReadOnlyMemory<float>)null;
Debug.Assert(rom.IsEmpty);

rom = ((float[])null!).AsMemory();
Debug.Assert(rom.IsEmpty);

rom = JsonSerializer.Deserialize<float[]>("null");
Debug.Assert(rom.IsEmpty);

it breaks my expectations that this:

rom = JsonSerializer.Deserialize<ReadOnlyMemory<float>>("null"); // boom

throws an exception:

Unhandled exception. System.Text.Json.JsonException: The JSON value could not be converted to System.ReadOnlyMemory`1[System.Single]. Path: $ | LineNumber: 0 | BytePositionInLine: 4.
   at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value, Boolean& isPopulatedValue)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.Deserialize(Utf8JsonReader& reader, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo`1 jsonTypeInfo, Nullable`1 actualByteCount)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo`1 jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions