I have a json file as follows
{
"desc": "my desc",
"lang": "en",
"issue": {
"date": "2024-09-01",
"title": "Empowering Razor Club"
},
"stars": [
{
"id": 1,
"value": 5
},
{
"id": 2,
"value": 4
}
]
}
This json structure is fixed and won’t change but the value can change. I want create a method to update particular property value and save back to file.
Using Newtonsoft.Json SelectToken
is easy by placing dot (.) for nested properties or even arrays such as "issue.title"
or "stars[0].value"
. When it comes to System.Text.Json
I find it harder.
private void UpdateJsonValue(string path, object value)
{
var json = "the above sample"
var node = JsonNode.Parse(json);
node[path] = JsonValue.Create(value); //error's here
json = node.ToJsonString();
//save json to file
}
UpdateJsonValue("issue.title", "Hello World");
UpdateJsonValue("stars[[1].value", 5);
So, how to get JsonNode
with nested properties?
2
Answers
Since
a) the structure is fixed
b) the value you are trying to change is particular and not generic,
deserialize into a class and serialize back into a file. This is how:
Consider the following method:
Use it in the following way: