Search code examples
c#jsonnode

C# migrating to Core, how can I retrieve a System.Text.Json.JsonNode element so I don't have to use .ToString()?


I'm migrating code from .Net Framework to Core and without getting into the reason why I want to do this, I'll just keep it simple and focus on what I want to do.

Let's say I have a jsonString that contains "Name". I parse the string with:

 JsonNode jn = JsonNode.Parse(jsonString);

And the get the value with:

string name = jn["Name"].ToString();

How can I override, extend, whatever so I don't have to use the .ToString() part and retrieve a JsonNode element value like:

string name = jn["Name"];

Solution

  • You can't and shouldn't for a reason: JsonNode can represent any type of value. You need to be explicit.

    edit for clarity: implicit conversion is something like

    string name = jn["Name"];
    

    while explicit conversion is

    string name = (string)jn["Name"];
    

    JsonNode doesn't have an implicit to string conversion. But there is an explicit one.

    Note: there is no way extend a class with an extra operator. You would need to edit the source (which is a bad idea). So what you want is not possible.

    Might I suggest a more robust approach? Define a type and deserialize that:

    public record MyData(string Name);
    var data = JsonSerializer.Deserialize<MyData>(jsonString);
    var name = data.Name;
    

    Or you can try the good-old "dictionary of strings" approach.

    var data = JsonSerializer.Deserialize<Dictionary<string,string>>(jsonString);
    var name = data["Name"];