Modifying JSON With JsonNode In C# & .NET
[C#, .NET, Json]
Over the years, we have extensively discussed the use of the native .NET JSON parser, System.Text.Json.
Almost always, we are reading and writing JSON (deserializing and serializing).
If you want to modify the JSON, you modify the object first, and then serialize it.
For example, take this type:
public record Cat(string Name, byte Legs);
We would create and serialize a Cat as follows:
var cat = new Cat("Tom", 4);
var options = new JsonSerializerOptions() { WriteIndented = true };
var json = JsonSerializer.Serialize(cat, options);
Console.WriteLine(json);
This would print the following:
{
"Name": "Tom",
"Legs": 4
}
Now, suppose you wanted to change the Legs of this cat.
Technically, this is not possible as a record type is immutable.
You would have to create another Cat like this:
var amputee = cat with { Legs = 3 };
json = JsonSerializer.Serialize(amputee, options);
Console.WriteLine(json);
This will print the following:
{
"Name": "Tom",
"Legs": 3
}
Suppose, for whatever reason, this was not an option, and you wanted to manipulate the JSON directly. Perhaps the JSON is being fetched from an external system.
Rather than manipulating the string directly, a far better approach is to use the JsonNode object. This creates a mutable object model that you can manipulate to your heart’s content.
Going back to our previous example, we can do something like this:
// Create a JonNode
var node = JsonNode.Parse(json);
if (node is null)
return;
// Read the properties we're interested in
var legs = node["Legs"]?.GetValue<int>();
var name = node["Name"]?.GetValue<string>();
// Output
Console.WriteLine($"{name} has {legs} Legs");
We can see here in the code that we are free to fetch strongly typed values from the JsonNode with type safety using the generic GetValue method.
I am using the ? conditional access operand because I am sure that node is not null, and neither are the values I am fetching.
As a JsonNode is mutable, we can mutate the JSON and do something like this:
// Mutate some properties
node["Legs"] = 3;
node["Name"] = "Top Cat";
We can then get our JSON from the node object as follows:
// Get the json from the node
json = node.ToJsonString(options);
// Output
Console.WriteLine(json);
Here we are using the ToJsonString method, passing our JsonSerializer options that we had created earlier.
This will print the following:
{
"Name": "Top Cat",
"Legs": 3
}
This JSON can now be used to construct an instance of the Cat type.
var modifiedCat = JsonSerializer.Deserialize<Cat>(json, options);
Console.WriteLine($"{modifiedCat.Name} has {modifiedCat.Legs} Legs");
This will look like this:

TLDR
You can use the JsonNode object for strongly typed access to JSON, as well as to manipulate JSON.
The code is in my GitHub.
Happy hacking!