Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to migrate Newtonsoft to System.Text.Json

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading