Home > Back-end >  How do you change the value of a JSONElement
How do you change the value of a JSONElement

Time:06-24

I actually don't think it's possible. But since I have not read it in the documentation and have not been able to confirm it by searching, I want to make absolutely sure.

Example:

    var myJsonString = "{\"report\": {\"Id\": \"aaakkj98898983\"}}";
    var jo = JsonDocument.Parse(myJsonString);
    var root = jo.RootElement;
    var id = root.GetProperty("report").GetProperty("Id");
    Console.WriteLine(id);

Perfect. Prints out the value of ID. Now I want to change the value of id such that it is anything else, say "HelloWorld". How do I do it?

CodePudding user response:

It is possible.

You can use JObject class in Newtonsoft.Json.Linq to modify JSON data.

Namespace:

 using Newtonsoft.Json;
 using Newtonsoft.Json.Linq;

Then :

var myJsonString = "{\"report\": {\"Id\": \"aaakkj98898983\"}}";
JObject jObject = JsonConvert.DeserializeObject(myJsonString) as JObject;


JToken jToken = jObject.SelectToken("report.Id");
jToken.Replace("HelloWorld"); 

string updatedJsonString = jObject.ToString(); 
Console.WriteLine(updatedJsonString);

Output:

{
  "report": {
    "Id": "HelloWorld"
  }
}

CodePudding user response:

You can serialize your json as an object, then you're able to mutate the data as desired.

Example:

    private class MyJsonObject
    {
        public Report Report { get; set; }
    }

    private class Report
    {
        public string Id { get; set; }
    }
    
    public static void Main(string[] args)
    {
        var myJsonString = "{\"Report\": {\"Id\": \"aaakkj98898983\"}}";
        var jo = JsonSerializer.Deserialize<MyJsonObject>(myJsonString);
        jo.Report.Id = "Some Id";

        Console.WriteLine(jo.Report.Id);
    }

UPDATE: Based on your comment, you can use dynamic type if you can't have concrete classes. System.Text.Json seems to have problems with dynamic, so I'm using Newtonsoft.Json for this example. I tested it locally and it seems to work.

    public static void Main(string[] args)
    {
        var myJsonString = "{\"Report\": {\"Id\": \"aaakkj98898983\"}}";

        dynamic jo = JObject.Parse(myJsonString);
        jo.Report.Id = "Some Id";

        Console.WriteLine(jo.Report.Id);
    }

CodePudding user response:

I wasn't conviced by the answers here so I kept investigating the suggestion to use JSonNodes. And this basically behaves the way I want.

var myJsonString = "{\"report\": {\"Id\": \"aaakkj98898983\"}}";
JsonNode jn = JsonNode.Parse(myJsonString)!;
JsonObject jo = jn.AsObject();
Console.WriteLine("===");
Console.WriteLine(jo["report"]!["Id"]);
jo["report"]!["Id"] = "Hello World";
Console.WriteLine("===");
Console.WriteLine(jo["report"]!["Id"]);
var options = new JsonSerializerOptions {WriteIndented = true};
Console.WriteLine("===");
Console.WriteLine(jo.ToJsonString(options));

I'm leaving the link here to a more full example where you can create as many random structures as you want (I suspect that this will carry a huge performance hit, but it does do what I want).

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-use-dom-utf8jsonreader-utf8jsonwriter?pivots=dotnet-6-0#use-jsondocument-for-access-to-data

PS: Make sure to add:

using System.Text.Json.Nodes;

At the top of the .cs in order for the system to recognize the JSonNode.

  •  Tags:  
  • c#
  • Related