System.Text.Json.Nodes.JsonValue GetValue<T> after serialization

53 Views Asked by At

I am trying to use JsonValue as a property on a larger object to represent a serialized value (similar to JToken in Newtonsoft).

However, I am running into issues when a JsonValue is parsed.


using System.Text.Json.Nodes;

record Project(string Id);

internal class Program
{
    public static void Main(string[] args)
    {
        var p = new Project("Test");
        var jval1 = JsonValue.Create(p)!;

        // This works!
        var p1 = jval1.GetValue<Project>();

        var jval2 = JsonNode.Parse(jval1.ToJsonString());

        // This does not :(
        var p2 = jval2.GetValue<Project>();
    }
}

I can evaluate p1, but not p2, it throws: System.InvalidOperationException: 'The node must be of type 'JsonValue'.'

I see this is because the JsonValue.Parse method returns a JsonNode and not a JsonValue. But cannot find any API surface that allows for creation of JsonValue from string.

0

There are 0 best solutions below