I have the following method that takes in a string of JSON and adds a new property to it
private string AddRequesterToJson(string initialJson, string requestedBy)
{
var json = JObject.Parse(initialJson);
json.Add("requestedBy", requestedBy);
return json.ToString();
}
This works fine and adds the new property to the JSON but now I’m trying to remove Newtonsoft from the project but I’m having problems as as I can’t seem to do a .add after I convert the string to an object:
private string AddRequesterToJson(string initialJson, string requestedBy)
{
var json = JsonObject.Parse(initialJson);
if (json != null)
{
json.Add("requestedBy", requestedBy); // parse seems to create a json node instead of a json object so there is no add here
return json.ToJsonString();
}
return initialJson;
}
I have also tried using JsonDocument.Parse but that also doesn’t let me add a new property to it. Is there a way of adding a new property to the JSON string before outputting it again using System.Text.Json?
>Solution :
You can use something like that:
//using System.Text.Json.Nodes;
private string AddRequesterToJson(string initialJson, string requestedBy)
{
var json = JsonNode.Parse(initialJson);
json.AsObject().Add("requestedBy", requestedBy);
return json.ToString();
}
The "AsObject().Add" method will add a new element/node to the json object at the root level.