Wednesday, September 20, 2023

.NET 8.0: Additional JsonNode Functionality

.NET 8 offers some exciting updates to System.Text.Json.

One of my favorites of them is, now we have some handy additional functionalities on JsonNode. The JsonNode has following new methods:

namespace System.Text.Json.Nodes;

public partial class JsonNode
{
    // Creates a deep clone of the current node and all its descendants.
    public JsonNode DeepClone();

    // Returns true if the two nodes are equivalent JSON representations.
    public static bool DeepEquals(JsonNode? node1, JsonNode? node2);

    // Determines the JsonValueKind of the current node.
    public JsonValueKind GetValueKind(JsonSerializerOptions options = null);

    // If node is the value of a property in the parent object, returns its name.
    public string GetPropertyName();

    // If node is an element of a parent JsonArray, returns its index.
    public int GetElementIndex();

    // Replaces this instance with a new value, updating the parent node accordingly.
    public void ReplaceWith<T>(T value);
}

public partial class JsonArray
{
    // Returns an IEnumerable<T> view of the current array.
    public IEnumerable<T> GetValues<T>();
}

For example, GetValueKind can be a huge win. 

Consider the following example with .NET 8.

using System.Text.Json.Nodes;

JsonNode jsonNode = JsonNode.Parse("""
    {
        "name": "John Doe",
        "age": 42,
        "isMarried": true,
        "addresses":
        [
            { "street": "One Microsoft Way", "city": "Redmond" },
            { "street": "1st Street", "city": "New York" }
        ]
    }
    """
)!;

Console.WriteLine(jsonNode.GetValueKind());
//Object

Console.WriteLine(jsonNode["name"]!.GetValueKind());
//String

Console.WriteLine(jsonNode["age"]!.GetValueKind());
//Number

Console.WriteLine(jsonNode["isMarried"]!.GetValueKind());
//True

Console.WriteLine(jsonNode["addresses"]!.GetValueKind());
//Array

Imagine how much code we needed to write prior to .NET 8 to achieve the same.

Isn't this handy?

Read more:
   What’s new in System.Text.Json in .NET 8

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment