Skip to content

Deserialization of a JsonNode with string value fails #113926

@mkArtakMSFT

Description

@mkArtakMSFT

Description

I'm working on converting the Microsoft.AspNetCore.JsonPatch to System.Text.Json.
As I was doing this, I came across an issue, where deserializing a string value from within a JsonObject instance throws an error:

System.InvalidCastException: 'Unable to cast object of type 'System.Text.Json.Nodes.JsonValueOfElement' to type 'System.Text.Json.Nodes.JsonValuePrimitive`1[System.String]'.'

This exception was originally thrown at this call stack:
    System.Text.Json.ThrowHelper.ThrowInvalidCastException_DeserializeUnableToAssignValue(System.Type, System.Type)
    System.Text.Json.JsonSerializer.UnboxOnRead.__ThrowUnableToCastValue|50_0<T>(object)
    System.Text.Json.JsonSerializer.UnboxOnRead<T>(object)
    System.Text.Json.Serialization.JsonConverter<T>.TryRead(ref System.Text.Json.Utf8JsonReader, System.Type, System.Text.Json.JsonSerializerOptions, ref System.Text.Json.ReadStack, out T, out bool)
    System.Text.Json.Serialization.JsonConverter<T>.ReadCore(ref System.Text.Json.Utf8JsonReader, out T, System.Text.Json.JsonSerializerOptions, ref System.Text.Json.ReadStack)
v

I discussed this with @eiriktsarpalis and he confirmed that this is not an expected behavior and suggested me to file this issue.

Please note, that the first thought that came up was to not use node.GetType() and specify the type explicitly using a generic Deserialize method instead. However, that isn't an option in my scenario as I dynamically get to the property that needs to be acted on, and there is no static type information available at that point.

Reproduction Steps

[Fact]
public void Test()
{
    var model = new JsonObject([new("Email", "[email protected]")]);

    _ = model.TryGetPropertyValue("Email", out var node);

    var serialized = JsonSerializer.Serialize(node);
    var deserialized = JsonSerializer.Deserialize(serialized, node.GetType());
}

Expected behavior

The deserialization should succeed (most probably by using JsonNode type instead? - not sure about this though).

Actual behavior

An exception shared above is thrown.

Regression?

No response

Known Workarounds

If I try to use the Deserialize() overload, things work, but that's not the scenario I can utilize.

Configuration

.NET current (aspnetcore main branch).
OS: Windows x64
I don't think this is related to the environment by any means.

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions