1

I have a json file that looks something like this:

{
   "a":{
      "lot":"of",
      "random":"stuff"
   },
   "url":"https://a.url.I.want.to.change",
   "some":{
      "other":"very",
      "random":"stuff"
   }
}

I read that json from a file and I want to change exactly the url field and than I want to save it back to the file.
I am using System.Text.Json in the entire project and I don´t want to introduce a dependency to newtonsoft.json

I tried it using dynamic like this:

string json = File.ReadAllText(filepath);
dynamic settings = JsonSerializer.Deserialize<dynamic>(json);

settings.url = "https://my.new.url";   // <- that is the problem

File.WriteAllText(filepath, JsonSerializer.Serialize(settings));

and also like this:

settings["url"] = "https://my.new.url";

but none of the approaches work because JsonSerializer deserializes it into an JsonElement, which is readonly I think.

Has anyone an idea of how that could be solved?

dbc
  • 104,963
  • 20
  • 228
  • 340
JakobFerdinand
  • 1,087
  • 7
  • 20
  • 2
    Are you using .NET 6? Then easiest way is to deserialize to `JsonNode` as shown in e.g. [Modifying a JSON file using System.Text.Json](https://stackoverflow.com/a/59001666/3744182). – dbc Jul 04 '22 at 13:12
  • Yes I´m using .NET6. Thank you! That is exactly what I needed! :D – JakobFerdinand Jul 04 '22 at 13:32

1 Answers1

2

try this

    string json = File.ReadAllText(filepath);

    var settings  = JsonNode.Parse(json); 
    settings ["url"]= "new url";
    json=settings.ToJsonString(new JsonSerializerOptions { WriteIndented = true });

    File.WriteAllText(filepath, json);
Serge
  • 40,935
  • 4
  • 18
  • 45