Equivalent of JObject in System.Text.Json

As of Nov 2021, .NET 6 introduces the System.Text.Json.Nodes namespace which:

Provides types for handling an in-memory writeable document object
model (DOM) for random access of the JSON elements within a structured
view of the data

The four new types are JsonArray, JsonObject, JsonNode and JsonValue.
The closest type to JObject is JsonObject which offers similar functionality.

See below for some examples:

// create object manually using initializer syntax
JsonObject obj = new JsonObject
{
    ["Id"] = 3,
    ["Name"] = "Bob",
    ["DOB"] = new DateTime(2001, 02, 03),
    ["Friends"] = new JsonArray
    {
        new JsonObject 
        {
            ["Id"] = 2,
            ["Name"] = "Smith"
        },
        new JsonObject
        {
            ["Id"] = 4,
            ["Name"] = "Jones"
        } 
    }
};

// random access to values
int id = (int)obj["Id"];
DateTime dob = (DateTime)obj["DOB"];
string firstFriendName = (string)obj["Friends"][0]["Name"];

Some other cool things which now make using System.Text.Json much easier in .NET6 are listed below.

Parse, Create, and DOM Manipulation

// parse
var jsonObj = JsonNode.Parse(jsonString).AsObject();

If you have a JsonElement (perhaps after deserializing into dynamic, object, or JsonElement) you can call Create, now you have a navigable and writable DOM object:

// create
JsonObject obj = JsonObject.Create(jsonElement);

You can Add/Remove properties:

obj.Add("FullName", "Bob Smith");
bool successfullyRemoved = obj.Remove("Name");

Safely interrogate object for particular key using ContainsKey and TryGetPropertyValue (which returns a JsonNode):

if (obj.ContainsKey("Hobbies"))
    // do stuff

if (obj.TryGetPropertyValue("Hobbies", out JsonNode? node))
    // do stuff with node

Project and Filter data

It’s possible to use Linq to project and filter the JsonObject:

// select Keys
List<string> keys = obj.Select(node => node.Key).ToList();
// filter friends
var friends = obj["Friends"].AsArray()
             .Where(n => (int)n.AsObject()["Id"] > 2);

Deserialize Json

It’s now easy to deserialize the Json or deserialize a portion of the Json. This is useful when we only want to deserialize partial Json from the main object. For the example above we can deserialize the list of friends into a generic List<Friend> easily:

List<Friend> friends = obj["Friends"].AsArray().Deserialize<List<Friend>>();

where Deserilize<T>() is an extension method on JsonNode.

Serialize

It’s easy to serialize the JsonObject by using ToJsonString():

string s = obj.ToJsonString();

// write pretty json with WriteIndented
string s = obj.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));

In your particular case you could define JsonObject in your DTO:

public class MyDTO
{
    public JsonObject ExtractedData {get;set;}
}

Leave a Comment